Skip to content

Instantly share code, notes, and snippets.

@hillar
Created December 11, 2020 14:06
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hillar/00bc23edda53a0846be0f04db66524a6 to your computer and use it in GitHub Desktop.
Save hillar/00bc23edda53a0846be0f04db66524a6 to your computer and use it in GitHub Desktop.
import { manifest } from '@sapper/internal/manifest-server'
export const definition = () => {
const openapi = { openapi: '3.0.0', paths: {} }
const routes = manifest.server_routes
for (const route of routes) {
const pattern = route.pattern.toString()
let name = pattern.replace('^\\/', '').replace('\\/?$/', '')
let params
if (name.endsWith('\\/([^/]+?)')) {
let prms = '/foo'
name = name.replace('\\/([^/]+?)', '')
while (name.endsWith('\\/([^/]+?)')) {
name = name.replace('\\/([^/]+?)', '')
prms += '/foo'
}
name = name.replace(/\\/gm, '')
params = route.params(route.pattern.exec(name + prms))
}
name = name.replace(/\\/gm, '')
for (const method of Object.keys(route.handlers)) {
// last will win
//if (!openapi.paths[name])
openapi.paths[name] = {}
//if (!openapi.paths[name][method])
openapi.paths[name][method] = { parameters: [] }
openapi.paths[name][method].responses = { 200: { description: 'Default response' } }
if (params) {
for (const param of Object.keys(params)) {
openapi.paths[name][method].parameters.push({
name: param,
schema: {
type: 'string',
},
in: 'path',
required: true,
})
}
} // else { // allow mix path and query
let sc = route.handlers[method].toString().split('\n')
const matchfuncparams = /\((\b\w*\b),(\b\w*\b),(\b\w*\b)\)\{/
const maybe = matchfuncparams.exec(sc[0].replace(/\s/g, ''))
let req
if (maybe && maybe[1]) {
req = maybe[1]
sc.shift()
const matchspread = new RegExp('{(.*)}=' + req + '.query')
let prms
for (const l of sc) {
const maybe = matchspread.exec(l.replace(/\s/g, ''))
if (maybe && maybe[1]) {
prms = maybe[1].split(',')
break
}
}
if (prms) {
for (const param of prms) {
openapi.paths[name][method].parameters.push({
name: param,
schema: {
type: 'string',
},
in: 'query',
required: false,
})
}
}
}
}
}
return openapi
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment