feathersjs-ecosystem / feathers-swagger

Add documentation to your FeatherJS services and feed them to Swagger UI.
MIT License
226 stars 63 forks source link

Static generation #252

Open jamesvillarrubia opened 1 year ago

jamesvillarrubia commented 1 year ago

Is there a way to generate the swagger json or yml and statically store it? I want to be able to lock the specs down, so that code must conform to the spec instead of the spec just representing the code in flux.

Mairu commented 1 year ago

It is not that hard to create a script to do that. feathers-swagger adds the generated specification as a property to the app object. (The name of the property could be adjusted with the appProperty option)

To add the property to the typescript definitions you have to adjust the declarations.ts:

// The application instance type that will be used everywhere else
export type Application = FeathersApplication<ServiceTypes, Configuration> & {
  docs?: Record<string, unknown>;
};

Then you can create a script / entrypoint in the src directory, for example generate-swagger.ts

import fs from 'node:fs';
import path from 'node:path';
import { app } from './app';
import { logger } from './logger';

app.setup().then(() => {
  fs.writeFileSync(path.join(__dirname, '..', 'swagger.json'), JSON.stringify(app.docs));
  logger.info('Wrote swagger.json');
});

You can then run that script with: npx ts-node src/generate-swagger.ts

If you prefer yaml output, you can of course also add a yaml writer package and write the object as yaml.