Skip to content

Infisical is the open-source platform for securing secrets, certificates, access, and AI Agents.

13.0 KB
Raw Blame
// Code generated by oapi-codegen. DO NOT EDIT.

package projects

import (
	"context"
	"encoding/json"
	"errors"
	"fmt"
	"net/http"

	"github.com/doordash-oss/oapi-codegen-dd/v3/pkg/runtime"
	"github.com/go-chi/chi/v5"
	"github.com/infisical/api/internal/server/api/shared"
	apivalidator "github.com/infisical/api/internal/server/api/validator"
)

// OapiErrorKind represents the type of error that occurred during request processing.
type OapiErrorKind int

const (
	// OapiErrorKindParse indicates a parameter parsing error (invalid path/query/header parameter).
	OapiErrorKindParse OapiErrorKind = iota

	// OapiErrorKindDecode indicates a request body decoding error (invalid JSON, form data, etc.).
	OapiErrorKindDecode

	// OapiErrorKindValidation indicates a request validation error (failed schema validation).
	OapiErrorKindValidation

	// OapiErrorKindService indicates a service/business logic error returned by the service implementation.
	OapiErrorKindService
)

// OapiHandlerError represents an error that occurred during request handling (parse, decode, validation).
// When no typed error response is configured in the OpenAPI spec, this error type is used.
// Custom error handlers can type-assert to this type to access error details.
type OapiHandlerError struct {
	Kind          OapiErrorKind
	OperationID   string
	Message       string
	ParamName     string
	ParamLocation string
}

func (e OapiHandlerError) Error() string {
	return e.Message
}

// OapiErrorResponse is the default JSON error response structure used by OapiDefaultErrorHandler.
type OapiErrorResponse struct {
	Error         string `json:"error"`
	OperationID   string `json:"operation_id,omitempty"`
	ParamName     string `json:"param_name,omitempty"`
	ParamLocation string `json:"param_location,omitempty"`
}

// OapiErrorHandler handles errors that occur during request processing.
// Implement this interface to customize error responses, logging, and metrics.
type OapiErrorHandler interface {
	// HandleError writes an error response to w with the given status code.
	// The err is either an OapiHandlerError (for parse/decode/validation errors)
	// or a typed error matching the OpenAPI spec's error response schema.
	HandleError(w http.ResponseWriter, r *http.Request, statusCode int, err error)
}

// OapiDefaultErrorHandler provides the default error handling behavior.
// It writes JSON error responses. For OapiHandlerError, it uses OapiErrorResponse.
// For typed errors (from OpenAPI spec), it encodes them directly.
type OapiDefaultErrorHandler struct{}

// HandleError implements OapiErrorHandler with default JSON error responses.
func (h *OapiDefaultErrorHandler) HandleError(w http.ResponseWriter, r *http.Request, statusCode int, err error) {
	w.Header().Set("Content-Type", "application/json")
	w.WriteHeader(statusCode)

	if handlerErr, ok := err.(OapiHandlerError); ok {
		_ = json.NewEncoder(w).Encode(OapiErrorResponse{
			Error:         handlerErr.Message,
			OperationID:   handlerErr.OperationID,
			ParamName:     handlerErr.ParamName,
			ParamLocation: handlerErr.ParamLocation,
		})
		return
	}

	// Typed error from OpenAPI spec - encode directly
	_ = json.NewEncoder(w).Encode(err)
}

// ServiceInterface defines the service interface for business logic.
type ServiceInterface interface {
	// GetProjectsHealth Health check
	GetProjectsHealth(ctx context.Context) (*GetProjectsHealthResponseData, error)
	// CreateProject Create a project
	CreateProject(ctx context.Context, opts *CreateProjectServiceRequestOptions) (*CreateProjectResponseData, error)
}

// HTTPAdapter adapts the ServiceInterface to HTTP handlers.
// This struct is generated and should not be modified.
type HTTPAdapter struct {
	svc             ServiceInterface
	errHandler      OapiErrorHandler
	jsonBodyDecoder runtime.JSONBodyDecoderFunc
}

// NewHTTPAdapter creates a new HTTPAdapter wrapping the given service.
// If errHandler is nil, OapiDefaultErrorHandler is used.
func NewHTTPAdapter(svc ServiceInterface, errHandler OapiErrorHandler) *HTTPAdapter {
	if errHandler == nil {
		errHandler = &OapiDefaultErrorHandler{}
	}
	return &HTTPAdapter{svc: svc, errHandler: errHandler, jsonBodyDecoder: runtime.DecodeJSONBody}
}

// GetProjectsHealth handles GET /health
func (a *HTTPAdapter) GetProjectsHealth(w http.ResponseWriter, r *http.Request) {
	ctx := r.Context()

	// Call business logic
	resp, err := a.svc.GetProjectsHealth(ctx)
	if err != nil {
		code := http.StatusInternalServerError
		if resp != nil && resp.Status != 0 {
			code = resp.Status
		}
		var errResp *GetProjectsHealthErrorResponse
		if errors.As(err, &errResp) {
			code = 400
		}
		a.errHandler.HandleError(w, r, code, err)
		return
	}

	// Validate response
	if resp != nil && resp.Body != nil {
		if v, ok := any(resp.Body).(runtime.Validator); ok {
			if err := v.Validate(); err != nil {
				a.errHandler.HandleError(w, r, http.StatusInternalServerError, OapiHandlerError{
					Kind:        OapiErrorKindValidation,
					OperationID: "GetProjectsHealth",
					Message:     fmt.Sprintf("response validation failed: %v", err),
				})
				return
			}
		}
	}

	// Apply custom headers from response
	if resp != nil && resp.Headers != nil {
		for k, v := range resp.Headers {
			for _, val := range v {
				w.Header().Add(k, val)
			}
		}
	}

	// Determine status code
	status := 200
	if resp != nil && resp.Status != 0 {
		status = resp.Status
	}
	if w.Header().Get("Content-Type") == "" {
		w.Header().Set("Content-Type", "application/json")
	}
	w.WriteHeader(status)
	if resp != nil && resp.Body != nil {
		_ = json.NewEncoder(w).Encode(resp.Body)
	}
}

// CreateProject handles POST /
func (a *HTTPAdapter) CreateProject(w http.ResponseWriter, r *http.Request) {
	ctx := r.Context()
	opts := &CreateProjectServiceRequestOptions{}
	opts.RawRequest = r

	// Parse request body
	defer r.Body.Close()
	var body CreateProjectBody
	if err := a.jsonBodyDecoder(r.Body, &body); err != nil {
		a.errHandler.HandleError(w, r, http.StatusBadRequest, OapiHandlerError{
			Kind:        OapiErrorKindDecode,
			OperationID: "CreateProject",
			Message:     err.Error(),
		})
		return
	}
	opts.Body = &body
	// Validate request
	if err := opts.Validate(); err != nil {
		a.errHandler.HandleError(w, r, http.StatusBadRequest, OapiHandlerError{
			Kind:        OapiErrorKindValidation,
			OperationID: "CreateProject",
			Message:     err.Error(),
		})
		return
	}

	// Call business logic
	resp, err := a.svc.CreateProject(ctx, opts)
	if err != nil {
		code := http.StatusInternalServerError
		if resp != nil && resp.Status != 0 {
			code = resp.Status
		}
		var errResp *CreateProjectErrorResponse
		if errors.As(err, &errResp) {
			code = 400
		}
		a.errHandler.HandleError(w, r, code, err)
		return
	}

	// Validate response
	if resp != nil && resp.Body != nil {
		if v, ok := any(resp.Body).(runtime.Validator); ok {
			if err := v.Validate(); err != nil {
				a.errHandler.HandleError(w, r, http.StatusInternalServerError, OapiHandlerError{
					Kind:        OapiErrorKindValidation,
					OperationID: "CreateProject",
					Message:     fmt.Sprintf("response validation failed: %v", err),
				})
				return
			}
		}
	}

	// Apply custom headers from response
	if resp != nil && resp.Headers != nil {
		for k, v := range resp.Headers {
			for _, val := range v {
				w.Header().Add(k, val)
			}
		}
	}

	// Determine status code
	status := 201
	if resp != nil && resp.Status != 0 {
		status = resp.Status
	}
	if w.Header().Get("Content-Type") == "" {
		w.Header().Set("Content-Type", "application/json")
	}
	w.WriteHeader(status)
	if resp != nil && resp.Body != nil {
		_ = json.NewEncoder(w).Encode(resp.Body)
	}
}

// RouterOption is a function that configures the router.
type RouterOption func(*routerConfig)

type routerConfig struct {
	middlewares     []func(http.Handler) http.Handler
	errHandler      OapiErrorHandler
	jsonBodyDecoder runtime.JSONBodyDecoderFunc
}

// WithMiddleware adds middleware to the router.
func WithMiddleware(mw func(http.Handler) http.Handler) RouterOption {
	return func(cfg *routerConfig) {
		cfg.middlewares = append(cfg.middlewares, mw)
	}
}

// WithErrorHandler sets a custom error handler for the router.
// If not set, OapiOapiDefaultErrorHandler is used.
func WithErrorHandler(h OapiErrorHandler) RouterOption {
	return func(cfg *routerConfig) {
		cfg.errHandler = h
	}
}

// WithJSONBodyDecoder sets a custom function for decoding JSON request bodies.
// If not set, runtime.DecodeJSONBody is used.
func WithJSONBodyDecoder(fn runtime.JSONBodyDecoderFunc) RouterOption {
	return func(cfg *routerConfig) {
		cfg.jsonBodyDecoder = fn
	}
}

// NewRouter creates a new chi.Router with the given service implementation.
func NewRouter(svc ServiceInterface, opts ...RouterOption) chi.Router {
	cfg := &routerConfig{}
	for _, opt := range opts {
		opt(cfg)
	}

	r := chi.NewRouter()
	for _, mw := range cfg.middlewares {
		r.Use(mw)
	}

	adapter := NewHTTPAdapter(svc, cfg.errHandler)
	if cfg.jsonBodyDecoder != nil {
		adapter.jsonBodyDecoder = cfg.jsonBodyDecoder
	}
	r.Method("GET", "/health", http.HandlerFunc(adapter.GetProjectsHealth))
	r.Method("POST", "/", http.HandlerFunc(adapter.CreateProject))

	return r
}

type CreateProjectBody = CreateProjectRequest

// GetProjectsHealthResponseData wraps the success response with optional headers and status override.
type GetProjectsHealthResponseData struct {
	Body    *GetProjectsHealthResponse
	Headers http.Header
	Status  int // 0 = use default (200)
}

// NewGetProjectsHealthResponseData creates a new GetProjectsHealthResponseData with the given body.
func NewGetProjectsHealthResponseData(body *GetProjectsHealthResponse) *GetProjectsHealthResponseData {
	return &GetProjectsHealthResponseData{Body: body}
}

// WithHeaders sets custom headers on the response.
func (r *GetProjectsHealthResponseData) WithHeaders(h http.Header) *GetProjectsHealthResponseData {
	r.Headers = h
	return r
}

// WithStatus overrides the default status code.
func (r *GetProjectsHealthResponseData) WithStatus(code int) *GetProjectsHealthResponseData {
	r.Status = code
	return r
}

// CreateProjectResponseData wraps the success response with optional headers and status override.
type CreateProjectResponseData struct {
	Body    *CreateProjectResponseJSON
	Headers http.Header
	Status  int // 0 = use default (201)
}

// NewCreateProjectResponseData creates a new CreateProjectResponseData with the given body.
func NewCreateProjectResponseData(body *CreateProjectResponseJSON) *CreateProjectResponseData {
	return &CreateProjectResponseData{Body: body}
}

// WithHeaders sets custom headers on the response.
func (r *CreateProjectResponseData) WithHeaders(h http.Header) *CreateProjectResponseData {
	r.Headers = h
	return r
}

// WithStatus overrides the default status code.
func (r *CreateProjectResponseData) WithStatus(code int) *CreateProjectResponseData {
	r.Status = code
	return r
}

type GetProjectsHealthResponse = GetHealthResponse

type GetProjectsHealthErrorResponse shared.ValidationError

func (r GetProjectsHealthErrorResponse) Error() string {
	return "unmapped client error"
}

type GetProjectsHealthErrorResponseJSON shared.Error

type GetProjectsHealthErrorResponseJSON500 shared.Error

type CreateProjectResponseJSON = CreateProjectResponse

type CreateProjectErrorResponse shared.ValidationError

func (r CreateProjectErrorResponse) Error() string {
	return "unmapped client error"
}

type CreateProjectErrorResponseJSON shared.Error

type CreateProjectErrorResponseJSON500 shared.Error

// CreateProjectServiceRequestOptions holds all parameters for the CreateProject operation.
type CreateProjectServiceRequestOptions struct {
	Body *CreateProjectBody
	// RawRequest provides access to the underlying HTTP request for custom content type handling.
	RawRequest *http.Request
}

// Validate validates all the fields in the options.
func (o *CreateProjectServiceRequestOptions) Validate() error {
	var errors runtime.ValidationErrors

	if o.Body != nil {
		if v, ok := any(o.Body).(runtime.Validator); ok {
			if err := v.Validate(); err != nil {
				errors = errors.Append("Body", err)
			}
		}
	}
	if len(errors) == 0 {
		return nil
	}

	return errors
}

type GetHealthResponse struct {
	// Message Health check message
	Message string `json:"message" validate:"required"`
}

func (g GetHealthResponse) Validate() error {
	return runtime.ConvertValidatorError(typesValidator.Struct(g))
}

type CreateProjectRequest struct {
	// Name Project name
	Name string `json:"name" validate:"required,min=1"`

	// OrgID Organization ID
	OrgID string `json:"orgId" validate:"required"`
}

func (c CreateProjectRequest) Validate() error {
	return runtime.ConvertValidatorError(typesValidator.Struct(c))
}

type CreateProjectResponse struct {
	// ID Project ID
	ID string `json:"id" validate:"required"`

	// Name Project name
	Name string `json:"name" validate:"required"`

	// OrgID Organization ID
	OrgID string `json:"orgId" validate:"required"`
}

func (c CreateProjectResponse) Validate() error {
	return runtime.ConvertValidatorError(typesValidator.Struct(c))
}

type Error = shared.Error

type ValidationError = shared.ValidationError

type FieldError = shared.FieldError

type PaginationMeta = shared.PaginationMeta

var typesValidator = apivalidator.V