Created
November 30, 2021 00:56
-
-
Save harada-shota/1f2f27f1307683acab44efbd867eea78 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// .msw/openAPIUtils.ts | |
import type { | |
Endpoints, | |
ExampleKind, | |
Methods, | |
OpenAPISpec, | |
ResponseType, | |
} from "./openAPISpec"; | |
export class OpenAPISpecTools { | |
openAPISpec: OpenAPISpec; | |
constructor(openAPISpec: OpenAPISpec) { | |
this.openAPISpec = openAPISpec; | |
} | |
getMethodsBy<Path extends Endpoints>(endpoint: Path): Methods[] { | |
return Object.keys(this.openAPISpec.paths[endpoint]) as Methods[]; | |
} | |
getExamplesBy<Path extends Endpoints>(path: Path) { | |
return <Method extends Methods>(method: Method) => | |
( | |
status: string | |
): { [K in ExampleKind<Path, Method>]: ResponseType<Path, Method> } => { | |
const response = this.openAPISpec.paths[path][method].responses[status]; | |
if (response === undefined) { | |
throw new Error(`status: ${status} is not defined in path ${path}`); | |
} | |
const { examples } = response.content["application/json"]; | |
if (examples === undefined) { | |
throw new Error( | |
`There are not any examples of ${method} in path ${path}` | |
); | |
} | |
return examples as { | |
[K in ExampleKind<Path, Method>]: ResponseType<Path, Method>; | |
}; | |
}; | |
} | |
getExampleNamesBy<Path extends Endpoints>(path: Path) { | |
return <Method extends Methods>(method: Method) => | |
(status: string): ExampleKind<Path, Method>[] => | |
Object.keys(this.getExamplesBy(path)(method)(status)) as ExampleKind< | |
Path, | |
Method | |
>[]; | |
} | |
getExampleBy<Path extends Endpoints>(path: Path) { | |
return <Method extends Methods>(method: Method) => | |
(status: string) => | |
(exampleKind: ExampleKind<Path, Method>): ResponseType<Path, Method> => { | |
// eslint-disable-next-line @typescript-eslint/no-explicit-any | |
return (this.getExamplesBy(path)(method)(status) as any)[exampleKind] | |
.value; | |
}; | |
} | |
isValidExampleNameBy<Path extends Endpoints>(path: Path) { | |
return <Method extends Methods>(method: Method) => | |
(status: string) => | |
( | |
exampleName: string | |
): exampleName is ReturnType< | |
ReturnType<ReturnType<OpenAPISpecTools["getExampleNamesBy"]>> | |
>[number] => { | |
return ( | |
exampleName === null || | |
// eslint-disable-next-line @typescript-eslint/no-explicit-any | |
this.getExampleNamesBy(path)(method)(status).includes( | |
exampleName as any | |
) | |
); | |
}; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment