Add OpenAPI Script for generating API fetch methods #13
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Overview
Add root
scripts
directory which containsopenapi-codegen
CLI project.The goal of this project is to use the backend's auto-generated OpenAPI3 schema to generate frontend code for interfacing with the backend, specifically to be used with SvelteKit.
Run the command with
# The current working directory is scripts/openapi-codegen $ npx bun src/app.ts
This will generate three files in a new
dist/api
folder:models.ts
which exports the Entity type definitions;endpoints.ts
which exports the http fetch methods to interact with the API; andindex.ts
which allows you to import from theapi
folder instead of from the individual filesinstead of
Codegen Script Details
From the project directory
scripts/openapi-codegen
, run the following command to see the--help
screen:npx bun src/app.ts --help # or, if bun is installed on your machine bun src/app.ts --help
Four additional
npm
scripts have been added to theopenapi-codegen
package.json
file to save keystrokes on common tasks:$ npm run local
src/lib/api
$ npm run local:test
local
, but does a dry-run, logging to console instead of saving to disk$ npm run remote
src/lib/api
$ npm run remote:test
remote
, but does a dry-run, logging to console instead of saving to diskThe above scripts all require that the current working directory be
scripts/openapi-codegen
. Two additional alias scripts have been added in the rootpackage.json
that can be run from the project's root directory:$npm run openapi-codegen:local
-> runs thelocal
script$npm run openapi-codegen:remote
-> runs theremote
scriptThe CLI commands can also be run individually using custom flags, for example:
# current working directory is scripts/openapi-codegen $ npx bun src/app.ts --local --output src/my/custom/output.json
See the associated
--help
command above for more details on all available options/flags.Sample Generated Code
models.ts
endpoints.ts