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

feat: generate type of responses #218

Merged
merged 2 commits into from
Nov 24, 2022
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
5 changes: 5 additions & 0 deletions aspida.config.js
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,11 @@ module.exports = [
input: 'samples/request-bodies',
outputEachDir: true,
openapi: { inputFile: 'samples/request-bodies.yml' }
},
{
input: 'samples/responses',
outputEachDir: true,
openapi: { inputFile: 'samples/responses.yml' }
}
// {
// input: 'samples/path-at-mark',
Expand Down
34 changes: 34 additions & 0 deletions samples/responses.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
openapi: 3.0.0
info:
version: 1.0.0
title: Sample
paths:
/users:
get:
summary: get users
operationId: post-users
responses:
'200':
$ref: '#/components/responses/UserResponseBody'
description: OK
description: ''
components:
schemas:
User:
type: object
properties:
id:
type: string
name:
type: string
required:
- id
- name
responses:
UserResponseBody:
content:
application/json:
schema:
type: array
items:
$ref: '#/components/schemas/User'
21 changes: 21 additions & 0 deletions samples/responses/$api.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
import type { AspidaClient, BasicHeaders } from 'aspida'
import type { Methods as Methods0 } from './users'

const api = <T>({ baseURL, fetch }: AspidaClient<T>) => {
const prefix = (baseURL === undefined ? '' : baseURL).replace(/\/$/, '')
const PATH0 = '/users'
const GET = 'GET'

return {
users: {
get: (option?: { config?: T | undefined } | undefined) =>
fetch<Methods0['get']['resBody'], BasicHeaders, Methods0['get']['status']>(prefix, PATH0, GET, option).json(),
$get: (option?: { config?: T | undefined } | undefined) =>
fetch<Methods0['get']['resBody'], BasicHeaders, Methods0['get']['status']>(prefix, PATH0, GET, option).json().then(r => r.body),
$path: () => `${prefix}${PATH0}`
}
}
}

export type ApiInstance = ReturnType<typeof api>
export default api
7 changes: 7 additions & 0 deletions samples/responses/@types/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
/* eslint-disable */
export type User = {
id: string
name: string
}

export type UserResponseBody = User[]
19 changes: 19 additions & 0 deletions samples/responses/users/$api.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
import type { AspidaClient, BasicHeaders } from 'aspida'
import type { Methods as Methods0 } from '.'

const api = <T>({ baseURL, fetch }: AspidaClient<T>) => {
const prefix = (baseURL === undefined ? '' : baseURL).replace(/\/$/, '')
const PATH0 = '/users'
const GET = 'GET'

return {
get: (option?: { config?: T | undefined } | undefined) =>
fetch<Methods0['get']['resBody'], BasicHeaders, Methods0['get']['status']>(prefix, PATH0, GET, option).json(),
$get: (option?: { config?: T | undefined } | undefined) =>
fetch<Methods0['get']['resBody'], BasicHeaders, Methods0['get']['status']>(prefix, PATH0, GET, option).json().then(r => r.body),
$path: () => `${prefix}${PATH0}`
}
}

export type ApiInstance = ReturnType<typeof api>
export default api
9 changes: 9 additions & 0 deletions samples/responses/users/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
/* eslint-disable */
import type * as Types from '../@types'

export type Methods = {
get: {
status: 200
resBody: Types.User[]
}
}
12 changes: 11 additions & 1 deletion src/buildV3.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ import getDirName from './builderUtils/getDirName'
import schemas2Props from './builderUtils/schemas2Props'
import parameters2Props from './builderUtils/parameters2Props'
import requestBodies2Props from './builderUtils/requestBodies2Props'
import responses2Props from './builderUtils/responses2Props'

const methodNames = ['get', 'post', 'put', 'delete', 'head', 'options', 'patch'] as const

Expand All @@ -31,6 +32,7 @@ export default (openapi: OpenAPIV3.Document) => {
const schemas = schemas2Props(openapi.components?.schemas, openapi) || []
const parameters = parameters2Props(openapi.components?.parameters, openapi, false) || []
const requestBodies = requestBodies2Props(openapi.components?.requestBodies) || []
const responses = responses2Props(openapi.components?.responses) || []

files.push(
...Object.keys(openapi.paths)
Expand Down Expand Up @@ -368,7 +370,7 @@ export default (openapi: OpenAPIV3.Document) => {
)

const typesText =
parameters.length + schemas.length + requestBodies.length
parameters.length + schemas.length + requestBodies.length + responses.length
? [
...parameters.map(p => ({
name: p.name,
Expand All @@ -387,6 +389,14 @@ export default (openapi: OpenAPIV3.Document) => {
typeof r.value === 'string'
? r.value
: value2String(r.value, '').replace(/\n {2}/g, '\n')
})),
...responses.map(r => ({
name: r.name,
description: null,
text:
typeof r.value === 'string'
? r.value
: value2String(r.value, '').replace(/\n {2}/g, '\n')
}))
]
.map(p => `\n${description2Doc(p.description, '')}export type ${p.name} = ${p.text}\n`)
Expand Down
30 changes: 30 additions & 0 deletions src/builderUtils/responses2Props.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
import { OpenAPIV3 } from 'openapi-types'
import { isRefObject, defKey2defName, $ref2Type, schema2value } from './converters'
import { PropValue } from './props2String'

export type Response = { name: string; value: string | PropValue }

export default (bodies: OpenAPIV3.ComponentsObject['responses']) =>
bodies &&
Object.keys(bodies)
.map(defKey => {
const target = bodies[defKey]
let value: Response['value']

if (isRefObject(target)) {
value = $ref2Type(target.$ref)
} else {
const content =
target.content &&
Object.entries(target.content).find(([key]) => key.startsWith('application/'))?.[1]
if (!content) return null

const result = schema2value(content.schema, false)
if (!result) return null

value = result
}

return { name: defKey2defName(defKey), value }
})
.filter((v): v is Response => !!v)