Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion .github/workflows/release.yml
Original file line number Diff line number Diff line change
Expand Up @@ -69,4 +69,5 @@ jobs:
done
git tag "v$version"
git push origin "v$version"
gh release create "v$version" --generate-notes --verify-tag
(cd backend && npm ci && npm run openapi:generate -- "$version")
gh release create "v$version" backend/dist/openapi.yaml --generate-notes --verify-tag
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -62,6 +62,7 @@ Open any Component with a `backstage.io/source-location` annotation. A "Runtime
- [Usage: critical-path workflows](docs/usage.md)
- [Architecture and API reference](docs/architecture.md)
- [Fulfillment API for adapters](docs/fulfillment-api.md)
- [OpenAPI spec](docs/fulfillment-api.md#openapi-spec): generated from the backend routes and attached to every GitHub release
- [Releases](docs/releases.md)

## Ecosystem
Expand Down
87 changes: 81 additions & 6 deletions backend/package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

10 changes: 7 additions & 3 deletions backend/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -20,11 +20,14 @@
},
"scripts": {
"build": "tsc -p tsconfig.build.json",
"test": "jest"
"test": "jest",
"openapi:generate": "npm run build && node scripts/generate-openapi.js"
},
"dependencies": {
"@asteasolutions/zod-to-openapi": "^9.1.0",
"@backstage/backend-plugin-api": "^0.6.0",
"express": "^4.18.0"
"express": "^4.18.0",
"zod": "^4.6.7"
},
"devDependencies": {
"@types/express": "^4.17.0",
Expand All @@ -33,6 +36,7 @@
"jest": "^29.7.0",
"supertest": "^6.3.0",
"ts-jest": "^29.1.0",
"typescript": "^5.4.0"
"typescript": "^5.4.0",
"yaml": "^2.9.1"
}
}
11 changes: 11 additions & 0 deletions backend/scripts/generate-openapi.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
// Writes dist/openapi.yaml from the routes registered on the compiled router.
// Run via `npm run openapi:generate [version]`, which builds first.
const fs = require('fs');
const path = require('path');
const { stringify } = require('yaml');
const { generateOpenApiDocument } = require('../dist/openapi');

const version = process.argv[2] || require('../package.json').version;
const out = path.resolve(__dirname, '../dist/openapi.yaml');
fs.writeFileSync(out, stringify(generateOpenApiDocument(version)));
console.log(`Wrote ${out}`);
24 changes: 24 additions & 0 deletions backend/src/openapi.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
import express, { Router } from 'express';
import { generateOpenApiDocument } from './openapi';
import { validated } from './route';

describe('generateOpenApiDocument', () => {
it('documents every route registered on the router', () => {
const doc = generateOpenApiDocument('test');
expect(Object.keys(doc.paths ?? {})).toEqual(['/fulfillments']);
expect(Object.keys(doc.paths?.['/fulfillments'] ?? {}).sort()).toEqual(['get', 'post']);
expect(Object.keys(doc.components?.schemas ?? {})).toContain('FulfillmentRecord');
});

it('fails when a route is registered without validated()', () => {
const router = Router();
router.get(
'/documented',
validated({ description: 'ok', responses: { 200: { description: 'ok' } } }, (_i, res) =>
res.end(),
),
);
router.get('/undocumented', (_req: express.Request, res: express.Response) => res.end());
expect(() => generateOpenApiDocument('test', router)).toThrow('/undocumented');
});
});
60 changes: 60 additions & 0 deletions backend/src/openapi.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
import { OpenAPIRegistry, OpenApiGeneratorV3 } from '@asteasolutions/zod-to-openapi';
import { Router } from 'express';
import { DocumentedHandler } from './route';
import { createRouter } from './router';

type Method = 'get' | 'post' | 'put' | 'patch' | 'delete';

interface Layer {
route?: {
path: string;
methods: Record<string, boolean>;
stack: { handle: Partial<DocumentedHandler> }[];
};
}

/** Builds the OpenAPI document by walking the routes registered on the Express router. */
export function generateOpenApiDocument(version: string, router: Router = createRouter()) {
const registry = new OpenAPIRegistry();

for (const layer of router.stack as Layer[]) {
if (!layer.route) continue;
const docs = layer.route.stack.map(s => s.handle.docs).find(Boolean);
if (!docs) {
throw new Error(`Route ${layer.route.path} has no docs; wrap its handler with validated()`);
}
for (const method of Object.keys(layer.route.methods) as Method[]) {
registry.registerPath({
method,
path: layer.route.path,
description: docs.description,
request: {
...(docs.body && {
body: { required: true, content: { 'application/json': { schema: docs.body } } },
}),
...(docs.query && { query: docs.query }),
},
responses: Object.fromEntries(
Object.entries(docs.responses).map(([status, r]) => [
status,
{
description: r.description,
...(r.schema && { content: { 'application/json': { schema: r.schema } } }),
},
]),
),
});
}
}

return new OpenApiGeneratorV3(registry.definitions).generateDocument({
openapi: '3.0.3',
info: {
title: 'runtime-conditions',
version,
description: 'Fulfillment API for the Runtime Conditions Backstage plugin.',
license: { name: 'MIT' },
},
servers: [{ url: '/api/runtime-conditions' }],
});
}
Loading
Loading