- Notifications
You must be signed in to change notification settings - Fork4
Go API-first and Database-first demo app with OpenAPI v3 and sqlc/xo codegen, OIDC auth, React TypeScript frontend, end to end tracing with OpenTelemetry and a smart Bash repo task manager.
License
danicc097/openapi-go-gin-postgres-sqlc
Folders and files
Name | Name | Last commit message | Last commit date | |
---|---|---|---|---|
Repository files navigation
Example full stack app with an API-first and Database-first approach with OpenAPI v3, sqlc+xo codegen,generated backend, frontend client and validators and an unimaginative title.
An example fully featured app to showcase how an OpenAPI v3 spec and databaseschema become a real single source of truth at once. Anychange to it is validated and cascades down to:
frontend: autogenerated complex, customizable and fully type-safe UI formsbased on the OpenAPI spec converted to JSONschema. Generated API queries (
orval
). User-friendly generated client-sidevalidation(viareact-hook-form
andajv
plus customizedkin-openapi
errormessages for backend errors). Check out the frontend home page for available links.backend: generated Gin server (custom
oapi-codegen
and post-generation).Request and response validation (kin-openapi
). Generated CRUD and index queries viaxo
and custom queries viasqlc
by leveraging customxo
template generationthat ensures compatibility. Integrated OpenID Connect client viazitadel/oidc
(and dockerized authorization server for development incmd/oidc-server
based on reusable mock server with generics inoidc-server). App events processingvia Server Sent Events.Queries generated by
xo
usepgx
exclusively and includespagination, indexes, soft delete handling, extensible queries (parameterizedwhere
,having
clauses), joins andmuch more (seexo integrationtests) that will get you95% there without resorting to ad-hoc queries. Found an edge case or want additional functionality just foryour DB needs? Just editxo-templates/
, since codegen is interpreted byyaegi
. Additionally, byusingpgx
, models can be easily re-exported as usable OpenAPI schemas viaopenapi-go
and some magic Bash and Go utility programs that keep generatedcode in order.Since using DB models in all backend layers is considered an anti-pattern atsome level of model complexity, you're not tied to generated schemas from DBmodels.Any struct can become a spec schema via
openapi-go
struct tags and somesimple bash code behind to grab them, with minimal caveats. Seerest
package. It is even possible to reference openapi spec models in yourxo
generated models, as long as they don't create any circular dependencies.Since at the last generation step we generate all spec schemas back to Go models withoapi-codegen
toa sharedmodels
package, this is not an issue (although you'd have tochoose what models to use, since there'll duplication for the modelsthat were already generated byopenapi-go
in the first place - ideally, use theoriginals).
Additionally, it features OpenTelemetry in both browser (automatic andmanual instrumentation) and backend services (manual instrumentation) viaJaeger, TimescaleDB andPromscale (discontinued, should look at options likemimir
).
You get dynamicx
function andx
options parameters documentationandautocompletion (complete -C project project
) forfree (from your own source itself and comments)so they're always up to date without any repetitive work: add/remove functionsand flags at will.Custom internal autocompletion functions for eachx
function orx
option can beeasily setup.
All calls tox
functions are logged (distinguishing stdout and stderr) for easier parallel execution and nestedcalls tracking:
And help for anyx
function is easily searchable when the app inevitably growswith--x-help
:
Fill in.env.template
's:
find. -name".env*.template"
Fordev
environment, you may useenv.ci
as a starting point,replacingci
withdev
and usingREVERSE_PROXY_API_PREFIX=""
since it will runthe backend without docker containers.
Assuming a recent Ubuntu release:
sudo apt install direnv -ydirenv allow# you can also customize direnv with .envrc.local as you would a regular .envrc, see examplecp openapi-go.code-workspace.example openapi-go.code-workspace# edit as desiredproject bootstrap# dependency and tools interactive installationproject recreate-shared-servicesproject genproject db.initial-dataproject run.all
For first test run:
project test.backend.setupproject test.backendproject test.frontend
bin/deploy-instrumentation
Db struct mappings can be extended with SQL column comments, joined with&&
:
properties
:<p1>,<p2>,...
private
: exclude a field from JSON.not-required
: make a schema field not required.hidden
: exclude field from OpenAPI generation.refs-ignore
: generate a field whose constraints are ignored by the referenced table,i.e. no joins will be generated.share-ref-constraints
: for a FK column, it will generate the same M2O and M2M join fields the ref column has.
type
: override the type annotation with an existing spec schema. Also allowscomplex JSON columns to be encoded and decoded thanks topgx
.cardinality
:<O2O|M2O|M2M>
to generate/override joins explicitly. Only O2O is inferred.tags
: append literal struct tag strings.
Structs inmodels.spec.go
will be generated viaopenapi-go
and replaced inthe spec. Make sure they don't clash with existingmodels
names or db tables.
Combines db codegen via a customxo
alongside spec schemas codegen for ease of use.
Seeproject test.create-crud-gen
's implementation for an example workflow to create avariety of implemented CRUD endpoints and relevant tests for a given databasetable.This is a one-off script per table.
Endpoints are exclusively managed through the spec and created/kept up to datein their respective files aggregated bytags
(limited to one)via codegen and AST modifications. This ensures the server always implements thespec.
For endpoint implementation, only method bodies are to be modified.
Component schemas:
x-gen-struct
generates a schema from a struct and keeps it up to date,which can be tagged with OpenAPI fields (via openapi-go).Possible structs to generate from are listed ininternal/codegen/structs.gen.go
indexed byx-gen-struct
.Packages to generate structs from are added adhoc (currently rest and models packages only)Note that rest package structs are generated without prefix since theyare the base of the spec - else prefix is the pascal cased package name.The value ofx-gen-struct
must match the schema name, to prevent duplicates andconfusing definitions.To use a yet to be generatedrest
package struct in specpaths
, simply use the$ref
without creating any schema and it will be autogenerated later if it doesn't exist(only forrest
package structs, since any other should not be used as request/response in thefirst place).x-spec-rest-type
: set to true to mark rest types (i.e. request, responses, query params...) that are manually defined in the spec instead of structs inmodels.spec.go
.Path operations:x-required-scopes
defines required scopes for a request.x-required-role
defines the minimum required role for a request.
Simplified:
- Nested functions in
project
'sx
functions will break automaticdocumentation for that particular function due to a bug indeclare
where the last nested function linenumber is returned instead of the parent.
Meaningful project name.
System design docs/diagrams.
About
Go API-first and Database-first demo app with OpenAPI v3 and sqlc/xo codegen, OIDC auth, React TypeScript frontend, end to end tracing with OpenTelemetry and a smart Bash repo task manager.
Topics
Resources
License
Uh oh!
There was an error while loading.Please reload this page.
Stars
Watchers
Forks
Packages0
Uh oh!
There was an error while loading.Please reload this page.
Contributors3
Uh oh!
There was an error while loading.Please reload this page.