-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
72 lines (58 loc) · 1.72 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
'use strict'
const path = require('node:path')
const fp = require('fastify-plugin')
const { glob } = require('glob')
const { checkSpecDir } = require('./lib/spec-dir')
const { mergeSpec } = require('./lib/merge-spec')
/**
* @type {import('fastify').FastifyPluginAsync}
*/
async function fastifyOpenapiServe (fastify, opts) {
const prefix = opts.routePrefix || '/docs'
const specDir = opts.specDir
checkSpecDir(fastify, specDir)
if (opts.merge && typeof opts.merge !== 'function') {
throw new Error('"merge" option must be a function')
}
const rootsSpec = Array.isArray(specDir) ? specDir : [specDir]
const specFiles = []
for (const specPath of rootsSpec) {
const files = await glob('**/*.{yaml,yml,json}', {
cwd: specPath, absolute: true, follow: true, nodir: true,
})
specFiles.push(...files.map((file) => {
return file.split(path.win32.sep).join(path.posix.sep)
}))
}
fastify.route({
method: 'GET',
url: `${prefix}/openapi.json`,
handler: async () => {
const mergedSpec = await mergeSpec(specFiles, {
merge: opts.merge,
specDefinition: opts.specDefinition,
})
return mergedSpec
},
})
fastify.route({
method: 'GET',
url: `${prefix}/openapi.yaml`,
handler: async (_, reply) => {
const mergedSpec = await mergeSpec(specFiles, {
merge: opts.merge,
specDefinition: opts.specDefinition,
yaml: true
})
return reply
.type('application/x-yaml')
.send(mergedSpec)
},
})
}
module.exports = fp(fastifyOpenapiServe, {
fastify: '5.x',
name: 'fastify-openapi-serve',
})
module.exports.default = fastifyOpenapiServe
module.exports.fastifyOpenapiServe = fastifyOpenapiServe