Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

swagger-cli validateがvalidとなるapi.jsonを作れるようにする #12403

Merged
merged 11 commits into from
Nov 22, 2023
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
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@
### Server
- Fix: 時間経過により無効化されたアンテナを再有効化したとき、サーバ再起動までその状況が反映されないのを修正 #12303
- Fix: ロールタイムラインが保存されない問題を修正
- Fix: api.jsonの生成ロジックを改善 #12402

## 2023.11.1

Expand Down
8 changes: 8 additions & 0 deletions packages/backend/generate_api_json.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
import { loadConfig } from './built/config.js'
import { genOpenapiSpec } from './built/server/api/openapi/gen-spec.js'
import { writeFileSync } from "node:fs";

const config = loadConfig();
const spec = genOpenapiSpec(config);

writeFileSync('./built/api.json', JSON.stringify(spec), 'utf-8');
3 changes: 2 additions & 1 deletion packages/backend/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,8 @@
"jest-and-coverage": "cross-env NODE_ENV=test node --experimental-vm-modules --experimental-import-meta-resolve node_modules/jest/bin/jest.js --coverage --forceExit",
"jest-clear": "cross-env NODE_ENV=test node --experimental-vm-modules --experimental-import-meta-resolve node_modules/jest/bin/jest.js --clearCache",
"test": "pnpm jest",
"test-and-coverage": "pnpm jest-and-coverage"
"test-and-coverage": "pnpm jest-and-coverage",
"generate-api-json": "node ./generate_api_json.js"
},
"optionalDependencies": {
"@swc/core-android-arm64": "1.3.11",
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,12 +16,9 @@ export const meta = {
requireCredential: false,

res: {
oneOf: [{
type: 'object',
ref: 'FederationInstance',
}, {
type: 'null',
}],
type: 'object',
optional: false, nullable: true,
ref: 'FederationInstance',
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

type: 'null'は定義されない書式らしいです…
代わりに、res直下のoptionalまたはnullableをtrueにすると、レスポンスのHTTPステータス一覧に204が生えるようにしています。

},
} as const;

Expand Down
42 changes: 29 additions & 13 deletions packages/backend/src/server/api/openapi/gen-spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
*/

import type { Config } from '@/config.js';
import endpoints from '../endpoints.js';
import endpoints, { IEndpoint } from '../endpoints.js';
import { errors as basicErrors } from './errors.js';
import { schemas, convertSchemaToOpenApiSchema } from './schemas.js';

Expand Down Expand Up @@ -33,16 +33,17 @@ export function genOpenapiSpec(config: Config) {
schemas: schemas,

securitySchemes: {
ApiKeyAuth: {
type: 'apiKey',
in: 'body',
name: 'i',
bearerAuth: {
type: 'http',
scheme: 'bearer',
},
},
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

inには"header"、"query"、"cookie"のみ設定できるとのことでした…
先人がどう解決したのか調べましたが、bodyにパラメータとして記述することを選んでいたので、それに倣いました

},
};

for (const endpoint of endpoints.filter(ep => !ep.meta.secure)) {
// 書き換えたりするのでディープコピーしておく。そのまま編集するとメモリ上の値が汚れて次回以降の出力に影響する
const copiedEndpoints = JSON.parse(JSON.stringify(endpoints)) as IEndpoint[];
for (const endpoint of copiedEndpoints.filter(ep => !ep.meta.secure)) {
const errors = {} as any;

if (endpoint.meta.errors) {
Expand Down Expand Up @@ -79,6 +80,13 @@ export function genOpenapiSpec(config: Config) {
schema.required = [...schema.required ?? [], 'file'];
}

if (schema.required && schema.required.length <= 0) {
// 空配列は許可されない
schema.required = undefined;
}

const hasBody = (schema.type === 'object' && schema.properties && Object.keys(schema.properties).length >= 1);

const info = {
operationId: endpoint.name,
summary: endpoint.name,
Expand All @@ -92,17 +100,19 @@ export function genOpenapiSpec(config: Config) {
} : {}),
...(endpoint.meta.requireCredential ? {
security: [{
ApiKeyAuth: [],
bearerAuth: [],
}],
} : {}),
requestBody: {
required: true,
content: {
[requestType]: {
schema,
...(hasBody ? {
requestBody: {
required: true,
content: {
[requestType]: {
schema,
},
},
},
},
} : {}),
responses: {
...(endpoint.meta.res ? {
'200': {
Expand All @@ -118,6 +128,11 @@ export function genOpenapiSpec(config: Config) {
description: 'OK (without any results)',
},
}),
...(endpoint.meta.res?.optional === true || endpoint.meta.res?.nullable === true ? {
'204': {
description: 'OK (without any results)',
},
} : {}),
'400': {
description: 'Client error',
content: {
Expand Down Expand Up @@ -190,6 +205,7 @@ export function genOpenapiSpec(config: Config) {
};

spec.paths['/' + endpoint.name] = {
...(endpoint.meta.allowGet ? { get: info } : {}),
post: info,
};
}
Expand Down
10 changes: 8 additions & 2 deletions packages/backend/src/server/api/openapi/schemas.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,10 +7,16 @@ import type { Schema } from '@/misc/json-schema.js';
import { refs } from '@/misc/json-schema.js';

export function convertSchemaToOpenApiSchema(schema: Schema) {
const res: any = schema;
// optional, refはスキーマ定義に含まれないので分離しておく
// eslint-disable-next-line @typescript-eslint/no-unused-vars
const { optional, ref, ...res }: any = schema;

if (schema.type === 'object' && schema.properties) {
res.required = Object.entries(schema.properties).filter(([k, v]) => !v.optional).map(([k]) => k);
const required = Object.entries(schema.properties).filter(([k, v]) => !v.optional).map(([k]) => k);
if (required.length > 0) {
// 空配列は許可されない
res.required = required;
}

for (const k of Object.keys(schema.properties)) {
res.properties[k] = convertSchemaToOpenApiSchema(schema.properties[k]);
Expand Down