Skip to content

feat: 実行時にレスポンスの型チェックを行うように #2619

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

Open
wants to merge 4 commits into
base: main
Choose a base branch
from
Open
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 package.json
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,7 @@
"@quasar/extras": "1.16.17",
"@sevenc-nanashi/utaformatix-ts": "npm:@jsr/[email protected]",
"@std/path": "npm:@jsr/[email protected]",
"ajv": "8.17.1",
"async-lock": "1.4.1",
"dayjs": "1.11.13",
"electron-log": "5.3.1",
Expand Down
36 changes: 35 additions & 1 deletion pnpm-lock.yaml

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

15 changes: 8 additions & 7 deletions src/store/proxy.ts → src/store/proxy/index.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import { ProxyStoreState, ProxyStoreTypes, EditorAudioQuery } from "./type";
import { createPartialStore } from "./vuex";
import { ProxyStoreState, ProxyStoreTypes, EditorAudioQuery } from "../type";
import { createPartialStore } from "../vuex";
import { validateOpenApiResponse } from "./openapi";
import { createEngineUrl } from "@/domain/url";
import { isElectron, isProduction } from "@/helpers/platform";
import {
Expand Down Expand Up @@ -35,11 +36,11 @@ const proxyStoreCreator = (_engineFactory: IEngineConnectorFactory) => {
);
return Promise.resolve({
invoke: (v) => (arg) =>
// FIXME: anyを使わないようにする
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
// eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/no-unsafe-return
instance[v](arg) as any,
validateOpenApiResponse(
v,
// @ts-expect-error 動いているので無視
instance[v](arg),
),
});
},
},
Expand Down
108 changes: 108 additions & 0 deletions src/store/proxy/openapi.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,108 @@
import Ajv, { JSONSchemaType, ValidateFunction } from "ajv";
import openapi from "../../../openapi.json";
import { cloneWithUnwrapProxy } from "@/helpers/cloneWithUnwrapProxy";
import { DefaultApiInterface } from "@/openapi";

export const validateOpenApiResponse = createValidateOpenApiResponse();

function toCamelCase(str: string) {
return str.replace(/_./g, (s) => s.charAt(1).toUpperCase());
}

/** OpenAPIのレスポンスを検証する */
function createValidateOpenApiResponse() {
const ajv = new Ajv().addSchema({
$id: "openapi.json",
definitions: patchOpenApiJson(openapi).components.schemas,
});
const validatorCache = new Map<string, ValidateFunction>();

for (const path of Object.values(openapi.paths)) {
for (const rawMethod of Object.values(path)) {
const method = rawMethod as {
operationId: string;
responses: Record<
string,
{ content?: Record<string, { schema?: unknown }> }
>;
};
const schema = method.responses["200"]?.content?.["application/json"]
?.schema as JSONSchemaType<unknown>;
if (schema == null) {
continue;
}
validatorCache.set(
toCamelCase(method.operationId),
ajv.compile(patchOpenApiJson(schema)),
);
}
}

return <K extends keyof DefaultApiInterface>(
key: K,
response: ReturnType<DefaultApiInterface[K]>,
): ReturnType<DefaultApiInterface[K]> => {
return response.then((res) => {
const maybeValidator = validatorCache.get(key);
if (maybeValidator == null) {
return res;
}

if (!maybeValidator(res)) {
throw new Error(
`Response validation error in ${key}: ${ajv.errorsText(maybeValidator.errors)}`,
);
}

return res;
}) as ReturnType<DefaultApiInterface[K]>;
};
}

/**
* OpenAPIのスキーマを修正する。
*
* 具体的には以下の変更を行う:
* - `$ref`の参照先を`#/components/schemas/`から`openapi.json#/definitions/`に変更する
* - オブジェクトのプロパティ名をキャメルケースに変換する
*/
function patchOpenApiJson<T extends Record<string, unknown>>(schema: T): T {
return inner(cloneWithUnwrapProxy(schema)) as T;

function inner(schema: Record<string, unknown>): Record<string, unknown> {
if (schema["$ref"] != null) {
const ref = schema["$ref"];
if (typeof ref === "string") {
schema["$ref"] = ref.replace(
"#/components/schemas/",
"openapi.json#/definitions/",
);
}
}

if (
schema["type"] === "object" &&
typeof schema["properties"] === "object" &&
schema["properties"] != null &&
Array.isArray(schema["required"])
) {
schema["properties"] = Object.fromEntries(
Object.entries(schema["properties"]).map(([key, value]) => [
toCamelCase(key),
inner(value as Record<string, unknown>),
]),
);

schema["required"] = schema["required"].map((key: string) =>
toCamelCase(key),
);
}

for (const key in schema) {
if (typeof schema[key] === "object" && schema[key] != null) {
inner(schema[key] as Record<string, unknown>);
}
}
return schema;
}
}
Loading