Projektstart

This commit is contained in:
2026-01-22 15:49:12 +01:00
parent 7212eb6f7a
commit 57e5f652f8
10637 changed files with 2598792 additions and 64 deletions

View File

View File

@@ -0,0 +1,230 @@
'use strict'
const { test } = require('tap')
const Fastify = require('fastify')
const fastifyHelmet = require('@fastify/helmet')
const fastifySwagger = require('@fastify/swagger')
const fastifySwaggerUi = require('..')
const {
schemaQuerystring,
schemaBody,
schemaParams,
schemaSecurity,
swaggerOption
} = require('../examples/options')
const csp = require('../static/csp.json')
test('staticCSP = undefined', async (t) => {
t.plan(3)
const fastify = Fastify()
await fastify.register(fastifySwagger, swaggerOption)
await fastify.register(fastifySwaggerUi)
fastify.get('/', () => {})
fastify.post('/', () => {})
fastify.get('/example', schemaQuerystring, () => {})
fastify.post('/example', schemaBody, () => {})
fastify.get('/parameters/:id', schemaParams, () => {})
fastify.get('/example1', schemaSecurity, () => {})
const res = await fastify.inject({
method: 'GET',
url: '/documentation'
})
t.equal(res.statusCode, 200)
t.equal(typeof res.headers['content-security-policy'], 'undefined')
t.equal(typeof res.payload, 'string')
})
test('staticCSP = true', async (t) => {
t.plan(5)
const fastify = Fastify()
await fastify.register(fastifySwagger, swaggerOption)
await fastify.register(fastifySwaggerUi, {
staticCSP: true
})
fastify.get('/', () => { return '' })
fastify.post('/', () => {})
fastify.get('/example', schemaQuerystring, () => {})
fastify.post('/example', schemaBody, () => {})
fastify.get('/parameters/:id', schemaParams, () => {})
fastify.get('/example1', schemaSecurity, () => {})
{
const res = await fastify.inject({
method: 'GET',
url: '/documentation'
})
t.equal(res.statusCode, 200)
t.equal(res.headers['content-security-policy'], `default-src 'self'; base-uri 'self'; font-src 'self' https: data:; frame-ancestors 'self'; img-src 'self' data: validator.swagger.io; object-src 'none'; script-src 'self' ${csp.script.join(' ')}; script-src-attr 'none'; style-src 'self' https: ${csp.style.join(' ')}; upgrade-insecure-requests;`)
t.equal(typeof res.payload, 'string')
}
{
const res = await fastify.inject({
method: 'GET',
url: '/'
})
t.equal(res.statusCode, 200)
t.equal(typeof res.headers['content-security-policy'], 'undefined')
}
})
test('staticCSP = "default-src \'self\';"', async (t) => {
t.plan(5)
const fastify = Fastify()
await fastify.register(fastifySwagger, swaggerOption)
await fastify.register(fastifySwaggerUi, {
staticCSP: "default-src 'self';"
})
fastify.get('/', () => { return '' })
fastify.post('/', () => {})
fastify.get('/example', schemaQuerystring, () => {})
fastify.post('/example', schemaBody, () => {})
fastify.get('/parameters/:id', schemaParams, () => {})
fastify.get('/example1', schemaSecurity, () => {})
{
const res = await fastify.inject({
method: 'GET',
url: '/documentation'
})
t.equal(res.statusCode, 200)
t.equal(res.headers['content-security-policy'], "default-src 'self';")
t.equal(typeof res.payload, 'string')
}
{
const res = await fastify.inject({
method: 'GET',
url: '/'
})
t.equal(res.statusCode, 200)
t.equal(typeof res.headers['content-security-policy'], 'undefined')
}
})
test('staticCSP = object', async (t) => {
t.plan(5)
const fastify = Fastify()
await fastify.register(fastifySwagger, swaggerOption)
await fastify.register(fastifySwaggerUi, {
staticCSP: {
'default-src': ["'self'"],
'script-src': "'self'"
}
})
fastify.get('/', () => { return '' })
fastify.post('/', () => {})
fastify.get('/example', schemaQuerystring, () => {})
fastify.post('/example', schemaBody, () => {})
fastify.get('/parameters/:id', schemaParams, () => {})
fastify.get('/example1', schemaSecurity, () => {})
{
const res = await fastify.inject({
method: 'GET',
url: '/documentation'
})
t.equal(res.statusCode, 200)
t.equal(res.headers['content-security-policy'], "default-src 'self'; script-src 'self';")
t.equal(typeof res.payload, 'string')
}
{
const res = await fastify.inject({
method: 'GET',
url: '/'
})
t.equal(res.statusCode, 200)
t.equal(typeof res.headers['content-security-policy'], 'undefined')
}
})
test('transformStaticCSP = function', async (t) => {
t.plan(6)
const fastify = Fastify()
await fastify.register(fastifySwagger, swaggerOption)
await fastify.register(fastifySwaggerUi, {
staticCSP: "default-src 'self';",
transformStaticCSP: function (header) {
t.equal(header, "default-src 'self';")
return "default-src 'self'; script-src 'self';"
}
})
fastify.get('/', () => { return '' })
fastify.post('/', () => {})
fastify.get('/example', schemaQuerystring, () => {})
fastify.post('/example', schemaBody, () => {})
fastify.get('/parameters/:id', schemaParams, () => {})
fastify.get('/example1', schemaSecurity, () => {})
{
const res = await fastify.inject({
method: 'GET',
url: '/documentation'
})
t.equal(res.statusCode, 200)
t.equal(res.headers['content-security-policy'], "default-src 'self'; script-src 'self';")
t.equal(typeof res.payload, 'string')
}
{
const res = await fastify.inject({
method: 'GET',
url: '/'
})
t.equal(res.statusCode, 200)
t.equal(typeof res.headers['content-security-policy'], 'undefined')
}
})
test('transformStaticCSP = function, with @fastify/helmet', async (t) => {
t.plan(6)
const fastify = Fastify()
fastify.register(fastifyHelmet)
await fastify.register(fastifySwagger, swaggerOption)
await fastify.register(fastifySwaggerUi, {
transformStaticCSP: function (header) {
t.equal(header, "default-src 'self';base-uri 'self';font-src 'self' https: data:;form-action 'self';frame-ancestors 'self';img-src 'self' data:;object-src 'none';script-src 'self';script-src-attr 'none';style-src 'self' https: 'unsafe-inline';upgrade-insecure-requests")
return "default-src 'self'; script-src 'self';"
}
})
fastify.get('/', () => { return '' })
fastify.post('/', () => {})
fastify.get('/example', schemaQuerystring, () => {})
fastify.post('/example', schemaBody, () => {})
fastify.get('/parameters/:id', schemaParams, () => {})
fastify.get('/example1', schemaSecurity, () => {})
{
const res = await fastify.inject({
method: 'GET',
url: '/documentation'
})
t.equal(res.statusCode, 200)
t.equal(res.headers['content-security-policy'], "default-src 'self'; script-src 'self';")
t.equal(typeof res.payload, 'string')
}
{
const res = await fastify.inject({
method: 'GET',
url: '/'
})
t.equal(res.statusCode, 200)
t.equal(res.headers['content-security-policy'], "default-src 'self';base-uri 'self';font-src 'self' https: data:;form-action 'self';frame-ancestors 'self';img-src 'self' data:;object-src 'none';script-src 'self';script-src-attr 'none';style-src 'self' https: 'unsafe-inline';upgrade-insecure-requests")
}
})

View File

@@ -0,0 +1,18 @@
'use strict'
const { test } = require('tap')
const Fastify = require('fastify')
const fastifySwagger = require('@fastify/swagger')
const fastifySwaggerUi = require('../index')
test('fastify.swaggerCSP should exist', async (t) => {
t.plan(3)
const fastify = Fastify()
await fastify.register(fastifySwagger)
await fastify.register(fastifySwaggerUi)
t.ok(fastify.swaggerCSP)
t.ok(Array.isArray(fastify.swaggerCSP.script))
t.ok(Array.isArray(fastify.swaggerCSP.style))
})

View File

@@ -0,0 +1,140 @@
'use strict'
const { test } = require('tap')
const Fastify = require('fastify')
const yaml = require('yaml')
const fastifySwagger = require('@fastify/swagger')
const fastifySwaggerUi = require('../index')
const { swaggerOption, schemaBody } = require('../examples/options')
const authOptions = {
validate (username, password, req, reply, done) {
if (username === 'admin' && password === 'admin') {
done()
} else {
done(new Error('Winter is coming'))
}
},
authenticate: true
}
function basicAuthEncode (username, password) {
return 'Basic ' + Buffer.from(username + ':' + password).toString('base64')
}
test('hooks on static swagger', async t => {
const fastify = Fastify()
await fastify.register(require('@fastify/basic-auth'), authOptions)
await fastify.register(fastifySwagger, {
mode: 'static',
specification: {
path: './examples/example-static-specification.yaml'
}
})
await fastify.register(fastifySwaggerUi, {
uiHooks: {
onRequest: fastify.basicAuth
}
})
let res = await fastify.inject('/documentation')
t.equal(res.statusCode, 401, 'root auth required')
res = await fastify.inject('/documentation/yaml')
t.equal(res.statusCode, 401, 'auth required yaml')
res = await fastify.inject({
method: 'GET',
url: '/documentation/yaml',
headers: { authorization: basicAuthEncode('admin', 'admin') }
})
t.equal(res.statusCode, 200)
t.equal(res.headers['content-type'], 'application/x-yaml')
try {
yaml.parse(res.payload)
t.pass('valid swagger yaml')
} catch (err) {
t.fail(err)
}
res = await fastify.inject('/documentation/json')
t.equal(res.statusCode, 401, 'auth required json')
res = await fastify.inject({
method: 'GET',
url: '/documentation/json',
headers: { authorization: basicAuthEncode('admin', 'admin') }
})
t.equal(typeof res.payload, 'string')
t.equal(res.headers['content-type'], 'application/json; charset=utf-8')
try {
yaml.parse(res.payload)
t.pass('valid swagger json')
} catch (err) {
t.fail(err)
}
})
test('hooks on dynamic swagger', async t => {
const fastify = Fastify()
await fastify.register(require('@fastify/basic-auth'), authOptions)
await fastify.register(fastifySwagger, {
...swaggerOption
})
await fastify.register(fastifySwaggerUi, {
uiHooks: {
onRequest: fastify.basicAuth
}
})
fastify.post('/fooBar123', schemaBody, () => {})
let res = await fastify.inject('/documentation')
t.equal(res.statusCode, 401, 'root auth required')
res = await fastify.inject('/documentation/yaml')
t.equal(res.statusCode, 401, 'auth required yaml')
res = await fastify.inject('/documentation/json')
t.equal(res.statusCode, 401, 'auth required json')
res = await fastify.inject({
method: 'GET',
url: '/documentation/json',
headers: { authorization: basicAuthEncode('admin', 'admin') }
})
t.equal(typeof res.payload, 'string')
t.equal(res.headers['content-type'], 'application/json; charset=utf-8')
const swaggerObject = res.json()
t.ok(swaggerObject.paths)
t.ok(swaggerObject.paths['/fooBar123'])
})
test('catch all added schema', async t => {
const fastify = Fastify()
await fastify.register(fastifySwagger, {
openapi: {},
refResolver: {
buildLocalReference: (json, baseUri, fragment, i) => {
return json.$id || `def-${i}`
}
}
})
await fastify.register(fastifySwaggerUi)
fastify.addSchema({ $id: 'Root', type: 'object', properties: {} })
fastify.register(async function (instance) {
instance.addSchema({ $id: 'Instance', type: 'object', properties: {} })
await instance.register(async function (instance) {
instance.addSchema({ $id: 'Sub-Instance', type: 'object', properties: {} })
})
})
await fastify.ready()
const openapi = fastify.swagger()
t.same(Object.keys(openapi.components.schemas), ['Root', 'Instance', 'Sub-Instance'])
})

View File

@@ -0,0 +1,47 @@
'use strict'
const { test } = require('tap')
const Fastify = require('fastify')
const fastifySwagger = require('@fastify/swagger')
const fastifyHelmet = require('@fastify/helmet')
const fastifySwaggerUi = require('../index')
const swaggerCSP = require('../static/csp.json')
test('fastify will response swagger csp', async (t) => {
t.plan(1)
const scriptCSP = swaggerCSP.script.length > 0 ? ` ${swaggerCSP.script.join(' ')}` : ''
const styleCSP = swaggerCSP.style.length > 0 ? ` ${swaggerCSP.style.join(' ')}` : ''
const csp = `default-src 'self';img-src 'self' data: validator.swagger.io;script-src 'self'${scriptCSP};style-src 'self' https:${styleCSP};base-uri 'self';font-src 'self' https: data:;form-action 'self';frame-ancestors 'self';object-src 'none';script-src-attr 'none';upgrade-insecure-requests`
const fastify = Fastify()
await fastify.register(fastifySwagger)
await fastify.register(fastifySwaggerUi)
const scriptSrc = ["'self'"].concat(fastify.swaggerCSP.script)
const styleSrc = ["'self'", 'https:'].concat(fastify.swaggerCSP.style)
await fastify.register(fastifyHelmet, {
contentSecurityPolicy: {
directives: {
defaultSrc: ["'self'"],
imgSrc: ["'self'", 'data:', 'validator.swagger.io'],
scriptSrc,
styleSrc
}
}
})
// route for testing CSP headers
fastify.get('/', (req, reply) => {
reply.send({
foo: 'bar'
})
})
const res = await fastify.inject({
method: 'GET',
url: '/'
})
t.same(res.headers['content-security-policy'], csp)
})

View File

@@ -0,0 +1,38 @@
'use strict'
const { test } = require('tap')
const Fastify = require('fastify')
const fastifySwagger = require('@fastify/swagger')
const fastifySwaggerUi = require('../index')
test('Swagger source does not contain sourceMaps', async (t) => {
t.plan(2)
const fastify = Fastify()
await fastify.register(fastifySwagger)
await fastify.register(fastifySwaggerUi)
const res = await fastify.inject({
method: 'GET',
url: '/documentation/static/swagger-ui.js'
})
const includesSourceMap = res.payload.includes('sourceMappingURL')
t.equal(includesSourceMap, false)
t.equal(res.headers['content-type'], 'application/javascript; charset=UTF-8')
})
test('Swagger css does not contain sourceMaps', async (t) => {
t.plan(2)
const fastify = Fastify()
await fastify.register(fastifySwagger)
await fastify.register(fastifySwaggerUi)
const res = await fastify.inject({
method: 'GET',
url: '/documentation/static/swagger-ui.css'
})
const includesSourceMap = res.payload.includes('sourceMappingURL')
t.equal(includesSourceMap, false)
t.equal(res.headers['content-type'], 'text/css; charset=UTF-8')
})

View File

@@ -0,0 +1,718 @@
'use strict'
const t = require('tap')
const test = t.test
const Fastify = require('fastify')
const Swagger = require('@apidevtools/swagger-parser')
const yaml = require('yaml')
const fastifySwagger = require('@fastify/swagger')
const fastifySwaggerUi = require('../index')
const {
schemaQuerystring,
schemaBody,
schemaParams,
schemaSecurity,
swaggerOption
} = require('../examples/options')
const resolve = require('node:path').resolve
const readFileSync = require('node:fs').readFileSync
const schemaParamsWithoutDesc = {
schema: {
params: {
type: 'object',
properties: {
id: {
type: 'string'
}
}
}
}
}
const schemaParamsWithKey = {
schema: {
params: {
type: 'object',
properties: {
id: {
type: 'string',
description: 'user id'
},
key: {
type: 'string',
description: 'just some random key'
}
}
}
}
}
test('/documentation/json route', async (t) => {
t.plan(1)
const fastify = Fastify()
await fastify.register(fastifySwagger, swaggerOption)
await fastify.register(fastifySwaggerUi)
fastify.get('/', () => {})
fastify.post('/', () => {})
fastify.get('/example', schemaQuerystring, () => {})
fastify.post('/example', schemaBody, () => {})
fastify.get('/parameters/:id', schemaParams, () => {})
fastify.get('/example1', schemaSecurity, () => {})
const res = await fastify.inject({
method: 'GET',
url: '/documentation/json'
})
const payload = JSON.parse(res.payload)
await Swagger.validate(payload)
t.pass('valid swagger object')
})
test('fastify.swagger should return a valid swagger yaml', async (t) => {
t.plan(3)
const fastify = Fastify()
await fastify.register(fastifySwagger, swaggerOption)
await fastify.register(fastifySwaggerUi)
fastify.get('/', () => {})
fastify.post('/', () => {})
fastify.get('/example', schemaQuerystring, () => {})
fastify.post('/example', schemaBody, () => {})
fastify.get('/parameters/:id', schemaParams, () => {})
fastify.get('/example1', schemaSecurity, () => {})
fastify.all('/parametersWithoutDesc/:id', schemaParamsWithoutDesc, () => {})
const res = await fastify.inject({
method: 'GET',
url: '/documentation/yaml'
})
t.equal(typeof res.payload, 'string')
t.equal(res.headers['content-type'], 'application/x-yaml')
yaml.parse(res.payload)
t.pass('valid swagger yaml')
})
test('/documentation should display index html', async (t) => {
t.plan(4)
const fastify = Fastify()
await fastify.register(fastifySwagger, swaggerOption)
await fastify.register(fastifySwaggerUi)
fastify.get('/', () => {})
fastify.post('/', () => {})
fastify.get('/example', schemaQuerystring, () => {})
fastify.post('/example', schemaBody, () => {})
fastify.get('/parameters/:id', schemaParams, () => {})
fastify.get('/example1', schemaSecurity, () => {})
const res = await fastify.inject({
method: 'GET',
url: '/documentation'
})
t.equal(res.statusCode, 200)
t.equal(res.headers.location, undefined)
t.equal(typeof res.payload, 'string')
t.equal('text/html; charset=utf-8', res.headers['content-type'])
})
test('/documentation/ should display index html ', async (t) => {
t.plan(4)
const fastify = Fastify()
await fastify.register(fastifySwagger, swaggerOption)
await fastify.register(fastifySwaggerUi)
fastify.get('/', () => {})
fastify.post('/', () => {})
fastify.get('/example', schemaQuerystring, () => {})
fastify.post('/example', schemaBody, () => {})
fastify.get('/parameters/:id', schemaParams, () => {})
fastify.get('/example1', schemaSecurity, () => {})
const res = await fastify.inject({
method: 'GET',
url: '/documentation/'
})
t.equal(res.statusCode, 200)
t.equal(res.headers.location, undefined)
t.equal(typeof res.payload, 'string')
t.equal('text/html; charset=utf-8', res.headers['content-type'])
})
test('/v1/documentation should display index html', async (t) => {
t.plan(4)
const fastify = Fastify()
await fastify.register(fastifySwagger, swaggerOption)
await fastify.register(fastifySwaggerUi, { routePrefix: '/v1/documentation' })
fastify.get('/', () => {})
fastify.post('/', () => {})
fastify.get('/example', schemaQuerystring, () => {})
fastify.post('/example', schemaBody, () => {})
fastify.get('/parameters/:id', schemaParams, () => {})
fastify.get('/example1', schemaSecurity, () => {})
const res = await fastify.inject({
method: 'GET',
url: '/v1/documentation'
})
t.equal(res.statusCode, 200)
t.equal(res.headers.location, undefined)
t.equal(typeof res.payload, 'string')
t.equal('text/html; charset=utf-8', res.headers['content-type'])
})
test('/v1/documentation/ should display index html', async (t) => {
t.plan(4)
const fastify = Fastify()
await fastify.register(fastifySwagger, swaggerOption)
await fastify.register(fastifySwaggerUi, { routePrefix: '/v1/documentation' })
fastify.get('/', () => {})
fastify.post('/', () => {})
fastify.get('/example', schemaQuerystring, () => {})
fastify.post('/example', schemaBody, () => {})
fastify.get('/parameters/:id', schemaParams, () => {})
fastify.get('/example1', schemaSecurity, () => {})
const res = await fastify.inject({
method: 'GET',
url: '/v1/documentation/'
})
t.equal(res.statusCode, 200)
t.equal(res.headers.location, undefined)
t.equal(typeof res.payload, 'string')
t.equal('text/html; charset=utf-8', res.headers['content-type'])
})
test('/v1/foobar should display index html', async (t) => {
t.plan(4)
const fastify = Fastify()
fastify.register(async function (fastify, options) {
await fastify.register(fastifySwagger, swaggerOption)
await fastify.register(fastifySwaggerUi, { routePrefix: '/foobar', noRedirect: true })
fastify.get('/', () => {})
fastify.post('/', () => {})
fastify.get('/example', schemaQuerystring, () => {})
fastify.post('/example', schemaBody, () => {})
fastify.get('/parameters/:id', schemaParams, () => {})
fastify.get('/example1', schemaSecurity, () => {})
}, { prefix: '/v1' })
const res = await fastify.inject({
method: 'GET',
url: '/v1/foobar'
})
t.equal(res.statusCode, 200)
t.equal(res.headers.location, undefined)
t.equal(typeof res.payload, 'string')
t.equal('text/html; charset=utf-8', res.headers['content-type'])
})
test('/v1/foobar/ should display index html', async (t) => {
t.plan(4)
const fastify = Fastify()
fastify.register(async function (fastify, options) {
await fastify.register(fastifySwagger, swaggerOption)
await fastify.register(fastifySwaggerUi, { routePrefix: '/foobar' })
fastify.get('/', () => {})
fastify.post('/', () => {})
fastify.get('/example', schemaQuerystring, () => {})
fastify.post('/example', schemaBody, () => {})
fastify.get('/parameters/:id', schemaParams, () => {})
fastify.get('/example1', schemaSecurity, () => {})
}, { prefix: '/v1' })
const res = await fastify.inject({
method: 'GET',
url: '/v1/foobar/'
})
t.equal(res.statusCode, 200)
t.equal(res.headers.location, undefined)
t.equal(typeof res.payload, 'string')
t.equal('text/html; charset=utf-8', res.headers['content-type'])
})
test('with routePrefix: \'/\' should display index html', async (t) => {
t.plan(4)
const fastify = Fastify()
await fastify.register(fastifySwagger, swaggerOption)
await fastify.register(fastifySwaggerUi, { routePrefix: '/' })
fastify.get('/foo', () => {})
const res = await fastify.inject({
method: 'GET',
url: '/'
})
t.equal(res.statusCode, 200)
t.equal(res.headers.location, undefined)
t.equal(typeof res.payload, 'string')
t.equal('text/html; charset=utf-8', res.headers['content-type'])
})
test('/documentation/static/:file should send back the correct file', async (t) => {
t.plan(21)
const fastify = Fastify()
await fastify.register(fastifySwagger, swaggerOption)
await fastify.register(fastifySwaggerUi)
fastify.get('/', () => {})
fastify.post('/', () => {})
fastify.get('/example', schemaQuerystring, () => {})
fastify.post('/example', schemaBody, () => {})
fastify.get('/parameters/:id', schemaParams, () => {})
fastify.get('/example1', schemaSecurity, () => {})
await fastify.ready()
{
const res = await fastify.inject({
method: 'GET',
url: '/documentation/static/index.html'
})
t.equal(res.statusCode, 302)
t.equal(res.headers.location, '/documentation/')
}
{
const res = await fastify.inject({
method: 'GET',
url: '/documentation/static/'
})
t.equal(typeof res.payload, 'string')
t.equal(res.headers['content-type'], 'text/html; charset=UTF-8')
t.equal(
readFileSync(
resolve(__dirname, '..', 'static', 'index.html'),
'utf8'
),
res.payload
)
t.ok(res.payload.indexOf('swagger-initializer.js') !== -1)
}
{
const res = await fastify.inject({
method: 'GET',
url: '/documentation/static/swagger-initializer.js'
})
t.equal(typeof res.payload, 'string')
t.equal(res.headers['content-type'], 'application/javascript; charset=utf-8')
t.ok(res.payload.indexOf('resolveUrl') !== -1)
}
{
const res = await fastify.inject({
method: 'GET',
url: '/documentation/static/oauth2-redirect.html'
})
t.equal(typeof res.payload, 'string')
t.equal(res.headers['content-type'], 'text/html; charset=UTF-8')
t.equal(
readFileSync(
resolve(__dirname, '..', 'static', 'oauth2-redirect.html'),
'utf8'
),
res.payload
)
}
{
const res = await fastify.inject({
method: 'GET',
url: '/documentation/static/swagger-ui.css'
})
t.equal(typeof res.payload, 'string')
t.equal(res.headers['content-type'], 'text/css; charset=UTF-8')
t.equal(
readFileSync(
resolve(__dirname, '..', 'static', 'swagger-ui.css'),
'utf8'
),
res.payload
)
}
{
const res = await fastify.inject({
method: 'GET',
url: '/documentation/static/swagger-ui-bundle.js'
})
t.equal(typeof res.payload, 'string')
t.equal(res.headers['content-type'], 'application/javascript; charset=UTF-8')
t.equal(
readFileSync(
resolve(__dirname, '..', 'static', 'swagger-ui-bundle.js'),
'utf8'
),
res.payload
)
}
{
const res = await fastify.inject({
method: 'GET',
url: '/documentation/static/swagger-ui-standalone-preset.js'
})
t.equal(typeof res.payload, 'string')
t.equal(res.headers['content-type'], 'application/javascript; charset=UTF-8')
t.equal(
readFileSync(
resolve(__dirname, '..', 'static', 'swagger-ui-standalone-preset.js'),
'utf8'
),
res.payload
)
}
})
test('/documentation/static/:file should send back file from baseDir', async (t) => {
t.plan(2)
const fastify = Fastify()
const uiConfig = {
baseDir: resolve(__dirname, '..', 'examples', 'static')
}
await fastify.register(fastifySwagger, swaggerOption)
await fastify.register(fastifySwaggerUi, uiConfig)
{
const res = await fastify.inject({
method: 'GET',
url: '/documentation/static/example-logo.svg'
})
t.equal(res.statusCode, 200)
t.equal(
res.payload,
readFileSync(
resolve(__dirname, '..', 'examples', 'static', 'example-logo.svg'),
'utf8'
)
)
}
})
test('/documentation/static/:file 404', async (t) => {
t.plan(2)
const fastify = Fastify()
await fastify.register(fastifySwagger, swaggerOption)
await fastify.register(fastifySwaggerUi)
fastify.get('/', () => {})
fastify.post('/', () => {})
fastify.get('/example', schemaQuerystring, () => {})
fastify.post('/example', schemaBody, () => {})
fastify.get('/parameters/:id', schemaParams, () => {})
fastify.get('/example1', schemaSecurity, () => {})
const res = await fastify.inject({
method: 'GET',
url: '/documentation/static/stuff.css'
})
const payload = JSON.parse(res.payload)
t.equal(res.statusCode, 404)
t.match(payload, {
error: 'Not Found',
statusCode: 404
})
})
test('/documentation2/json route (overwrite)', async (t) => {
t.plan(1)
const fastify = Fastify()
await fastify.register(fastifySwagger, swaggerOption)
await fastify.register(fastifySwaggerUi, { routePrefix: '/documentation2' })
fastify.get('/', () => {})
fastify.post('/', () => {})
fastify.get('/example', schemaQuerystring, () => {})
fastify.post('/example', schemaBody, () => {})
fastify.get('/parameters/:id', schemaParams, () => {})
fastify.get('/example1', schemaSecurity, () => {})
fastify.get('/parameters/:id/:key', schemaParamsWithKey, () => {})
const res = await fastify.inject({
method: 'GET',
url: '/documentation2/json'
})
const payload = JSON.parse(res.payload)
await Swagger.validate(payload)
t.pass('valid swagger object')
})
test('/documentation/:myfile should return 404 in dynamic mode', async (t) => {
t.plan(1)
const fastify = Fastify()
await fastify.register(fastifySwagger, swaggerOption)
await fastify.register(fastifySwaggerUi)
const res = await fastify.inject({
method: 'GET',
url: '/documentation/swagger-ui.js'
})
t.equal(res.statusCode, 404)
})
test('/documentation/:myfile should run custom NotFoundHandler in dynamic mode', async (t) => {
t.plan(1)
const fastify = Fastify()
const notFoundHandler = function (req, reply) {
reply.code(410).send()
}
fastify.setNotFoundHandler(notFoundHandler)
await fastify.register(fastifySwagger, swaggerOption)
await fastify.register(fastifySwaggerUi)
const res = await fastify.inject({
method: 'GET',
url: '/documentation/swagger-ui.js'
})
t.equal(res.statusCode, 410)
})
test('/documentation/* should not return module files when baseDir not set', async (t) => {
t.plan(1)
const fastify = Fastify()
await fastify.register(fastifySwagger, swaggerOption)
await fastify.register(fastifySwaggerUi)
const res = await fastify.inject({
method: 'GET',
url: '/documentation/README.md'
})
t.equal(res.statusCode, 404)
})
test('should return silent log level of route /documentation', async (t) => {
const fastify = Fastify()
fastify.addHook('onRoute', function (route) {
t.equal(route.logLevel, 'silent')
})
await fastify.register(fastifySwagger, swaggerOption)
await fastify.register(fastifySwaggerUi, { logLevel: 'silent' })
const res = await fastify.inject({
method: 'GET',
url: '/documentation/'
})
t.equal(res.statusCode, 200)
t.equal(res.headers['content-type'], 'text/html; charset=utf-8')
})
test('should return empty log level of route /documentation', async (t) => {
const fastify = Fastify()
fastify.addHook('onRoute', function (route) {
t.equal(route.logLevel, '')
})
await fastify.register(fastifySwagger, swaggerOption)
await fastify.register(fastifySwaggerUi)
const res = await fastify.inject({
method: 'GET',
url: '/documentation/'
})
t.equal(res.statusCode, 200)
t.equal(res.headers['content-type'], 'text/html; charset=utf-8')
})
test('/documentation should display index html with correct asset urls', async (t) => {
t.plan(6)
const fastify = Fastify()
await fastify.register(fastifySwagger, swaggerOption)
await fastify.register(fastifySwaggerUi, { theme: { js: [{ filename: 'theme-js.js' }] } })
const res = await fastify.inject({
method: 'GET',
url: '/documentation'
})
t.equal(res.payload.includes('href="./documentation/static/index.css"'), true)
t.equal(res.payload.includes('src="./documentation/static/theme/theme-js.js"'), true)
t.equal(res.payload.includes('href="./documentation/index.css"'), false)
t.equal(res.payload.includes('src="./documentation/theme/theme-js.js"'), false)
let cssRes = await fastify.inject({
method: 'GET',
url: '/documentation/static/index.css'
})
t.equal(cssRes.statusCode, 200)
cssRes = await fastify.inject({
method: 'GET',
url: './documentation/static/index.css'
})
t.equal(cssRes.statusCode, 200)
})
/**
* This emulates when the server is inside an NGINX application that routes by path
*/
test('/documentation should display index html with correct asset urls when nested', async (t) => {
t.plan(5)
const fastify = Fastify()
await fastify.register(
async () => {
await fastify.register(fastifySwagger, swaggerOption)
await fastify.register(fastifySwaggerUi, { theme: { js: [{ filename: 'theme-js.js' }] } })
},
{
prefix: '/swagger-app'
}
)
const res = await fastify.inject({
method: 'GET',
url: '/swagger-app/documentation'
})
t.equal(res.payload.includes('href="./documentation/static/index.css"'), true)
t.equal(res.payload.includes('src="./documentation/static/theme/theme-js.js"'), true)
t.equal(res.payload.includes('href="./documentation/index.css"'), false)
t.equal(res.payload.includes('src="./documentation/theme/theme-js.js"'), false)
const cssRes = await fastify.inject({
method: 'GET',
url: '/swagger-app/documentation/static/index.css'
})
t.equal(cssRes.statusCode, 200)
})
test('/documentation/ should display index html with correct asset urls', async (t) => {
t.plan(4)
const fastify = Fastify()
await fastify.register(fastifySwagger, swaggerOption)
await fastify.register(fastifySwaggerUi, { theme: { js: [{ filename: 'theme-js.js' }] } })
const res = await fastify.inject({
method: 'GET',
url: '/documentation/'
})
t.equal(res.payload.includes('href="./static/index.css"'), true)
t.equal(res.payload.includes('src="./static/theme/theme-js.js"'), true)
t.equal(res.payload.includes('href="./index.css"'), false)
t.equal(res.payload.includes('src="./theme/theme-js.js"'), false)
})
test('/docs should display index html with correct asset urls when documentation prefix is set', async (t) => {
t.plan(4)
const fastify = Fastify()
await fastify.register(fastifySwagger, swaggerOption)
await fastify.register(fastifySwaggerUi, { theme: { js: [{ filename: 'theme-js.js' }] }, routePrefix: '/docs' })
const res = await fastify.inject({
method: 'GET',
url: '/docs'
})
t.equal(res.payload.includes('href="./docs/static/index.css"'), true)
t.equal(res.payload.includes('src="./docs/static/theme/theme-js.js"'), true)
t.equal(res.payload.includes('href="./docs/index.css"'), false)
t.equal(res.payload.includes('src="./docs/theme/theme-js.js"'), false)
})
test('/docs should display index html with correct asset urls when documentation prefix is set with no leading slash', async (t) => {
t.plan(4)
const fastify = Fastify()
await fastify.register(fastifySwagger, swaggerOption)
await fastify.register(fastifySwaggerUi, { theme: { js: [{ filename: 'theme-js.js' }] }, routePrefix: 'docs' })
const res = await fastify.inject({
method: 'GET',
url: '/docs'
})
t.equal(res.payload.includes('href="docs/static/index.css"'), true)
t.equal(res.payload.includes('src="docs/static/theme/theme-js.js"'), true)
t.equal(res.payload.includes('href="docs/index.css"'), false)
t.equal(res.payload.includes('src="docs/theme/theme-js.js"'), false)
})
test('/docs/ should display index html with correct asset urls when documentation prefix is set', async (t) => {
t.plan(4)
const fastify = Fastify()
await fastify.register(fastifySwagger, swaggerOption)
await fastify.register(fastifySwaggerUi, { theme: { js: [{ filename: 'theme-js.js' }] }, routePrefix: '/docs' })
const res = await fastify.inject({
method: 'GET',
url: '/docs/'
})
t.equal(res.payload.includes('href="./static/index.css"'), true)
t.equal(res.payload.includes('src="./static/theme/theme-js.js"'), true)
t.equal(res.payload.includes('href="./index.css"'), false)
t.equal(res.payload.includes('src="./theme/theme-js.js"'), false)
})
test('/documentation/ should display index html with correct asset urls', async (t) => {
t.plan(4)
const fastify = Fastify()
await fastify.register(fastifySwagger, swaggerOption)
await fastify.register(fastifySwaggerUi, { theme: { js: [{ filename: 'theme-js.js' }] } })
const res = await fastify.inject({
method: 'GET',
url: '/documentation/'
})
t.equal(res.payload.includes('href="./static/index.css"'), true)
t.equal(res.payload.includes('src="./static/theme/theme-js.js"'), true)
t.equal(res.payload.includes('href="./index.css"'), false)
t.equal(res.payload.includes('src="./theme/theme-js.js"'), false)
})
test('/docs should display index html with correct asset urls when documentation prefix is set', async (t) => {
t.plan(4)
const fastify = Fastify()
await fastify.register(fastifySwagger, swaggerOption)
await fastify.register(fastifySwaggerUi, { theme: { js: [{ filename: 'theme-js.js' }] }, routePrefix: '/docs' })
const res = await fastify.inject({
method: 'GET',
url: '/docs'
})
t.equal(res.payload.includes('href="./docs/static/index.css"'), true)
t.equal(res.payload.includes('src="./docs/static/theme/theme-js.js"'), true)
t.equal(res.payload.includes('href="./docs/index.css"'), false)
t.equal(res.payload.includes('src="./docs/theme/theme-js.js"'), false)
})
test('/docs/ should display index html with correct asset urls when documentation prefix is set', async (t) => {
t.plan(4)
const fastify = Fastify()
await fastify.register(fastifySwagger, swaggerOption)
await fastify.register(fastifySwaggerUi, { theme: { js: [{ filename: 'theme-js.js' }] }, routePrefix: '/docs' })
const res = await fastify.inject({
method: 'GET',
url: '/docs/'
})
t.equal(res.payload.includes('href="./static/index.css"'), true)
t.equal(res.payload.includes('src="./static/theme/theme-js.js"'), true)
t.equal(res.payload.includes('href="./index.css"'), false)
t.equal(res.payload.includes('src="./theme/theme-js.js"'), false)
})

View File

@@ -0,0 +1,128 @@
'use strict'
const { test } = require('tap')
const serialize = require('../lib/serialize')
test('serialize', async (t) => {
t.plan(8)
t.test('boolean', t => {
t.plan(2)
t.equal(serialize(true), 'true')
t.equal(serialize(false), 'false')
})
t.test('number', t => {
t.plan(7)
t.equal(serialize(0), '0')
t.equal(serialize(1), '1')
t.equal(serialize(1.0), '1')
t.equal(serialize(1.01), '1.01')
t.equal(serialize(Infinity), 'Infinity')
t.equal(serialize(-Infinity), '-Infinity')
t.equal(serialize(NaN), 'NaN')
})
t.test('string', t => {
t.plan(3)
t.equal(serialize('0'), '"0"')
t.equal(serialize('abc'), '"abc"')
t.equal(serialize('"a'), '"\\\"a"') // eslint-disable-line no-useless-escape
})
t.test('bigint', t => {
t.plan(3)
t.equal(serialize(0n), '0n')
t.equal(serialize(1000000000n), '1000000000n')
t.equal(serialize(-9999n), '-9999n')
})
t.test('function', t => {
t.plan(7)
t.equal(serialize(function a () {}), 'function a () {}')
t.equal(serialize(async function a () {}), 'async function a () {}')
t.equal(serialize(() => {}), '() => {}')
t.equal(serialize(async () => {}), 'async () => {}')
t.equal(serialize(() => Date.now), '() => Date.now')
t.equal(serialize(function () {}), 'function () {}')
t.equal(serialize(async function () {}), 'async function () {}')
})
t.test('undefined', t => {
t.plan(1)
t.equal(serialize(undefined), 'undefined')
})
t.test('symbol', t => {
t.plan(2)
t.equal(serialize(Symbol('a')), 'Symbol("a")')
t.equal(serialize(Symbol()), 'Symbol()') // eslint-disable-line symbol-description
})
t.test('object', t => {
t.plan(7)
t.test('null', t => {
t.plan(1)
t.equal(serialize(null), 'null')
})
t.test('RegExp', t => {
t.plan(1)
t.equal(serialize(/0-9/gi), '/0-9/gi')
})
t.test('Date', t => {
t.plan(1)
t.equal(serialize(new Date(0)), 'new Date(0)')
})
t.test('Array', t => {
t.plan(5)
t.equal(serialize([]), '[]')
t.equal(serialize(['a']), '["a"]')
t.equal(serialize([1, 1n, 'a', true]), '[1,1n,"a",true]')
t.equal(serialize([{}]), '[{}]')
t.equal(serialize([{ a: [{}] }]), '[{"a":[{}]}]')
})
t.test('POJO', t => {
t.plan(3)
t.equal(serialize({}), '{}')
t.equal(serialize({ key: 'value' }), '{"key":"value"}')
t.equal(serialize({ null: null, undefined }), '{"null":null,"undefined":undefined}')
})
t.test('Set', t => {
t.plan(3)
t.equal(serialize(new Set()), 'new Set([])')
t.equal(serialize(new Set(['a'])), 'new Set(["a"])')
t.equal(serialize(new Set(['a', {}])), 'new Set(["a",{}])')
})
t.test('Map', t => {
t.plan(3)
t.equal(serialize(new Map()), 'new Map([])')
t.equal(serialize(new Map([['a', 1]])), 'new Map([["a",1]])')
const map = new Map()
map.set('b', 1)
t.equal(serialize(map), 'new Map([["b",1]])')
})
})
})

View File

@@ -0,0 +1,407 @@
'use strict'
const fs = require('node:fs')
const resolve = require('node:path').resolve
const { test } = require('tap')
const yaml = require('yaml')
const Fastify = require('fastify')
const fastifySwagger = require('@fastify/swagger')
const fastifySwaggerUi = require('../index')
const oauthRedirectHtml = fs.readFileSync(resolve(__dirname, '..', 'static', 'oauth2-redirect.html'), 'utf8')
const exampleStaticSpecificationYaml = fs.readFileSync(
resolve(__dirname, '..', 'examples', 'example-static-specification.yaml'),
'utf8'
)
test('swagger route returns yaml', async (t) => {
t.plan(3)
const config = {
mode: 'static',
specification: {
path: './examples/example-static-specification.yaml'
}
}
const fastify = Fastify()
await fastify.register(fastifySwagger, config)
await fastify.register(fastifySwaggerUi)
// check that yaml is there
const res = await fastify.inject({
method: 'GET',
url: '/documentation/yaml'
})
t.equal(typeof res.payload, 'string')
t.equal(res.headers['content-type'], 'application/x-yaml')
yaml.parse(res.payload)
t.pass('valid swagger yaml')
})
test('swagger route returns json', async (t) => {
t.plan(3)
const config = {
mode: 'static',
specification: {
path: './examples/example-static-specification.json'
}
}
const fastify = Fastify()
await fastify.register(fastifySwagger, config)
await fastify.register(fastifySwaggerUi)
// check that json is there
const res = await fastify.inject({
method: 'GET',
url: '/documentation/json'
})
t.equal(typeof res.payload, 'string')
t.equal(res.headers['content-type'], 'application/json; charset=utf-8')
yaml.parse(res.payload)
t.pass('valid swagger json')
})
test('postProcessor works, swagger route returns updated yaml', async (t) => {
t.plan(4)
const config = {
mode: 'static',
specification: {
path: './examples/example-static-specification.yaml',
postProcessor: function (swaggerObject) {
swaggerObject.servers[0].url = 'http://localhost:4000/'
return swaggerObject
}
}
}
const fastify = Fastify()
await fastify.register(fastifySwagger, config)
await fastify.register(fastifySwaggerUi)
// check that yaml is there
const res = await fastify.inject({
method: 'GET',
url: '/documentation/yaml'
})
t.equal(typeof res.payload, 'string')
t.equal(res.headers['content-type'], 'application/x-yaml')
yaml.parse(res.payload)
t.matchSnapshot(res.payload)
t.pass('valid swagger yaml')
})
test('swagger route returns explicitly passed doc', async (t) => {
t.plan(2)
const document = {
info: {
title: 'Test swagger',
description: 'testing the fastify swagger api',
version: '0.1.0'
}
}
const config = {
mode: 'static',
specification: {
document
}
}
const fastify = Fastify()
await fastify.register(fastifySwagger, config)
// check that json is there
const res = await fastify.inject({
method: 'GET',
url: '/documentation/json'
})
const payload = JSON.parse(res.payload)
t.matchSnapshot(JSON.stringify(payload, null, 2))
t.pass('valid explicitly passed spec document')
})
test('/documentation/:file should serve static file from the location of main specification file', async (t) => {
t.plan(4)
const config = {
mode: 'static',
specification: {
path: './examples/example-static-specification.yaml'
}
}
const uiConfig = {
baseDir: resolve(__dirname, '..', 'examples')
}
const fastify = Fastify()
await fastify.register(fastifySwagger, config)
await fastify.register(fastifySwaggerUi, uiConfig)
{
const res = await fastify.inject({
method: 'GET',
url: '/documentation/non-existing-file'
})
t.equal(res.statusCode, 404)
}
{
const res = await fastify.inject({
method: 'GET',
url: '/documentation/example-static-specification.yaml'
})
t.equal(res.statusCode, 200)
t.equal(exampleStaticSpecificationYaml, res.payload)
}
{
const res = await fastify.inject({
method: 'GET',
url: '/documentation/dynamic-swagger.js'
})
t.equal(res.statusCode, 200)
}
})
test('/documentation/non-existing-file calls custom NotFoundHandler', async (t) => {
t.plan(1)
const config = {
mode: 'static',
specification: {
path: './examples/example-static-specification.yaml'
}
}
const fastify = Fastify()
await fastify.register(fastifySwagger, config)
await fastify.register(fastifySwaggerUi)
fastify.setNotFoundHandler((request, reply) => {
reply.code(410).send()
})
const res = await fastify.inject({
method: 'GET',
url: '/documentation/some-file-that-does-not-exist.js'
})
t.equal(res.statusCode, 410)
})
test('/documentation/:file should be served from custom location', async (t) => {
t.plan(2)
const config = {
mode: 'static',
specification: {
path: './examples/example-static-specification.yaml',
baseDir: resolve(__dirname, '..', 'static')
}
}
const uiConfig = {
baseDir: resolve(__dirname, '..', 'static')
}
const fastify = Fastify()
await fastify.register(fastifySwagger, config)
await fastify.register(fastifySwaggerUi, uiConfig)
const res = await fastify.inject({
method: 'GET',
url: '/documentation/oauth2-redirect.html'
})
t.equal(res.statusCode, 200)
t.equal(oauthRedirectHtml, res.payload)
})
test('/documentation/:file should be served from custom location with trailing slash(es)', async (t) => {
t.plan(2)
const config = {
mode: 'static',
specification: {
path: './examples/example-static-specification.yaml'
}
}
const uiConfig = {
baseDir: resolve(__dirname, '..', 'static') + '/'
}
const fastify = Fastify()
await fastify.register(fastifySwagger, config)
await fastify.register(fastifySwaggerUi, uiConfig)
const res = await fastify.inject({
method: 'GET',
url: '/documentation/oauth2-redirect.html'
})
t.equal(res.statusCode, 200)
t.equal(oauthRedirectHtml, res.payload)
})
test('/documentation/yaml returns cache.swaggerString on second request in static mode', async (t) => {
t.plan(6)
const config = {
mode: 'static',
specification: {
path: './examples/example-static-specification.yaml'
}
}
const fastify = Fastify()
await fastify.register(fastifySwagger, config)
await fastify.register(fastifySwaggerUi)
{
const res = await fastify.inject({
method: 'GET',
url: '/documentation/yaml'
})
t.equal(typeof res.payload, 'string')
t.equal(res.headers['content-type'], 'application/x-yaml')
yaml.parse(res.payload)
t.pass('valid swagger yaml')
}
{
const res = await fastify.inject({
method: 'GET',
url: '/documentation/yaml'
})
t.equal(typeof res.payload, 'string')
t.equal(res.headers['content-type'], 'application/x-yaml')
yaml.parse(res.payload)
t.pass('valid swagger yaml')
}
})
test('/documentation/json returns cache.swaggerObject on second request in static mode', async (t) => {
t.plan(6)
const config = {
mode: 'static',
specification: {
path: './examples/example-static-specification.json'
}
}
const fastify = Fastify()
await fastify.register(fastifySwagger, config)
await fastify.register(fastifySwaggerUi)
{
const res = await fastify.inject({
method: 'GET',
url: '/documentation/json'
})
t.equal(typeof res.payload, 'string')
t.equal(res.headers['content-type'], 'application/json; charset=utf-8')
t.pass('valid swagger json')
}
{
const res = await fastify.inject({
method: 'GET',
url: '/documentation/json'
})
t.equal(typeof res.payload, 'string')
t.equal(res.headers['content-type'], 'application/json; charset=utf-8')
t.pass('valid swagger json')
}
})
test('/documentation/yaml returns cache.swaggerString on second request in dynamic mode', async (t) => {
t.plan(6)
const config = {
specification: {
path: './examples/example-static-specification.yaml'
}
}
const fastify = Fastify()
await fastify.register(fastifySwagger, config)
await fastify.register(fastifySwaggerUi)
{
const res = await fastify.inject({
method: 'GET',
url: '/documentation/yaml'
})
t.equal(typeof res.payload, 'string')
t.equal(res.headers['content-type'], 'application/x-yaml')
yaml.parse(res.payload)
t.pass('valid swagger yaml')
}
{
const res = await fastify.inject({
method: 'GET',
url: '/documentation/yaml'
})
t.equal(typeof res.payload, 'string')
t.equal(res.headers['content-type'], 'application/x-yaml')
yaml.parse(res.payload)
t.pass('valid swagger yaml')
}
})
test('/documentation/json returns cache.swaggerObject on second request in dynamic mode', async (t) => {
t.plan(6)
const config = {
specification: {
path: './examples/example-static-specification.json'
}
}
const fastify = Fastify()
await fastify.register(fastifySwagger, config)
await fastify.register(fastifySwaggerUi)
{
const res = await fastify.inject({
method: 'GET',
url: '/documentation/json'
})
t.equal(typeof res.payload, 'string')
t.equal(res.headers['content-type'], 'application/json; charset=utf-8')
t.pass('valid swagger json')
}
{
const res = await fastify.inject({
method: 'GET',
url: '/documentation/json'
})
t.equal(typeof res.payload, 'string')
t.equal(res.headers['content-type'], 'application/json; charset=utf-8')
t.pass('valid swagger json')
}
})

View File

@@ -0,0 +1,94 @@
'use strict'
const { test } = require('tap')
const Fastify = require('fastify')
const fastifySwagger = require('@fastify/swagger')
const fastifySwaggerUi = require('../index')
test('/documentation/static/swagger-initializer.js should have default uiConfig', async (t) => {
t.plan(2)
const fastify = Fastify()
await fastify.register(fastifySwagger)
await fastify.register(fastifySwaggerUi)
const res = await fastify.inject({
method: 'GET',
url: '/documentation/static/swagger-initializer.js'
})
t.equal(res.statusCode, 200)
t.ok(res.payload.includes('const config = {}'))
})
test('/documentation/static/swagger-initializer.js should have configurable uiConfig', async (t) => {
t.plan(2)
const fastify = Fastify()
await fastify.register(fastifySwagger)
await fastify.register(fastifySwaggerUi, {
// eslint-disable-next-line no-undef
uiConfig: { onComplete: () => { alert('test') } }
})
const res = await fastify.inject({
method: 'GET',
url: '/documentation/static/swagger-initializer.js'
})
t.equal(res.statusCode, 200)
t.ok(res.payload.includes("const config = {\"onComplete\":() => { alert('test') }}"))
})
test('/documentation/static/swagger-initializer.js should have default initOAuth', async (t) => {
t.plan(2)
const fastify = Fastify()
await fastify.register(fastifySwagger)
await fastify.register(fastifySwaggerUi)
const res = await fastify.inject({
method: 'GET',
url: '/documentation/static/swagger-initializer.js'
})
t.equal(res.statusCode, 200)
t.ok(res.payload.includes('ui.initOAuth({})'))
})
test('/documentation/static/swagger-initializer.js should have configurable initOAuth', async (t) => {
t.plan(2)
const fastify = Fastify()
await fastify.register(fastifySwagger)
await fastify.register(fastifySwaggerUi, {
initOAuth: {
clientId: 'someId'
}
})
const res = await fastify.inject({
method: 'GET',
url: '/documentation/static/swagger-initializer.js'
})
t.equal(res.statusCode, 200)
t.ok(res.payload.includes('ui.initOAuth({"clientId":"someId"})'))
})
test('customize logo', async (t) => {
const config = {
mode: 'static',
specification: {
path: './examples/example-static-specification.yaml'
}
}
const fastify = Fastify()
await fastify.register(fastifySwagger, config)
await fastify.register(fastifySwaggerUi, { logo: { type: 'image/png', content: 'foobar' } })
const res = await fastify.inject('/documentation/static/swagger-initializer.js')
t.equal(res.body.indexOf(Buffer.from('foobar').toString('base64')) > -1, true)
})

View File

@@ -0,0 +1,244 @@
'use strict'
const { test } = require('tap')
const Fastify = require('fastify')
const fastifySwagger = require('@fastify/swagger')
const fastifySwaggerUi = require('../index')
test('swagger route does not return additional theme', async (t) => {
const config = {
mode: 'static',
specification: {
path: './examples/example-static-specification.yaml'
}
}
t.plan(5)
const fastify = Fastify()
await fastify.register(fastifySwagger, config)
await fastify.register(fastifySwaggerUi, { theme: null })
const res = await fastify.inject({
method: 'GET',
url: '/documentation'
})
t.equal(typeof res.payload, 'string')
t.notMatch(res.payload, /theme\/special\.js/)
t.notMatch(res.payload, /theme\/favicon\.png/)
t.notMatch(res.payload, /theme\/theme\.css/)
t.equal(res.headers['content-type'], 'text/html; charset=utf-8')
})
test('swagger route returns additional theme', async (t) => {
const config = {
mode: 'static',
specification: {
path: './examples/example-static-specification.yaml'
}
}
t.plan(9)
const fastify = Fastify()
await fastify.register(fastifySwagger, config)
await fastify.register(fastifySwaggerUi, {
theme: {
js: [
{ filename: 'special.js', content: 'alert("loaded test-theme")' }
],
css: [
{ filename: 'theme.css', content: '* {border: 1px red solid;}' }
],
favicon: [
{
filename: 'favicon.png',
rel: 'icon',
sizes: '16x16',
type: 'image/png',
content: Buffer.from('iVBORw0KGgoAAAANSUhEUgAAAA8AAAAQCAQAAABjX+2PAAAAIGNIUk0AAHomAACAhAAA+gAAAIDoAAB1MAAA6mAAADqYAAAXcJy6UTwAAAACYktHRAD/h4/MvwAAAAd0SU1FB+cCEQ06N8A8CiUAAADnSURBVBjTrdE/K8QBAMbxz/0TLrnUWcTg7ySLewGEwWDRzSYpyULJbGG6wWBTlMEbkHsFNnVloAwXudIlnDru1O9nOCex3rM89TzL0/eh1Ypo//Zk5CdM6JP2IWFOxbmMKZVmPWzbrJSamG5FNXUFx42yV16oqCQUerNr2pghsSgS1sw4kxNVVvbu3rwjSwJ67Kgq2XMjtO/AnWsnVgwQNy6rQ8GkURWBpCebXnR5gA11j5b1OxT4EKq6dGurMWvQqqw2LPoUKDq1LqPzN4q0rCuvckbE/pOakHdhQfwvwKan8Nzad74AkR8/Ir6qAvAAAAAldEVYdGRhdGU6Y3JlYXRlADIwMjMtMDItMTdUMTM6NTg6NTUrMDA6MDBjkr64AAAAJXRFWHRkYXRlOm1vZGlmeQAyMDIzLTAyLTE3VDEzOjU4OjU1KzAwOjAwEs8GBAAAACh0RVh0ZGF0ZTp0aW1lc3RhbXAAMjAyMy0wMi0xN1QxMzo1ODo1NSswMDowMEXaJ9sAAAAASUVORK5CYII=', 'base64')
}
]
}
})
const res = await fastify.inject({
method: 'GET',
url: '/documentation'
})
t.equal(typeof res.payload, 'string')
t.match(res.payload, /theme\/special\.js/)
t.match(res.payload, /theme\/favicon\.png/)
t.match(res.payload, /theme\/theme\.css/)
t.equal(res.headers['content-type'], 'text/html; charset=utf-8')
{
const res = await fastify.inject({
method: 'GET',
url: '/documentation/static/theme/special.js'
})
t.equal(res.payload, 'alert("loaded test-theme")')
}
{
const res = await fastify.inject({
method: 'GET',
url: '/documentation/static/theme/favicon.png'
})
t.equal(res.statusCode, 200)
t.equal(res.headers['content-type'], 'image/png')
}
{
const res = await fastify.inject({
method: 'GET',
url: '/documentation/static/theme/theme.css'
})
t.equal(res.payload, '* {border: 1px red solid;}')
}
})
test('swagger route returns additional theme - only js', async (t) => {
const config = {
mode: 'static',
specification: {
path: './examples/example-static-specification.yaml'
}
}
t.plan(4)
const fastify = Fastify()
await fastify.register(fastifySwagger, config)
await fastify.register(fastifySwaggerUi, {
theme: {
js: [
{ filename: 'special.js', content: 'alert("loaded test-theme")' }
]
}
})
const res = await fastify.inject({
method: 'GET',
url: '/documentation'
})
t.equal(typeof res.payload, 'string')
t.match(res.payload, /theme\/special\.js/)
t.equal(res.headers['content-type'], 'text/html; charset=utf-8')
{
const res = await fastify.inject({
method: 'GET',
url: '/documentation/static/theme/special.js'
})
t.equal(res.payload, 'alert("loaded test-theme")')
}
})
test('swagger route returns additional theme - only css', async (t) => {
const config = {
mode: 'static',
specification: {
path: './examples/example-static-specification.yaml'
}
}
t.plan(4)
const fastify = Fastify()
await fastify.register(fastifySwagger, config)
await fastify.register(fastifySwaggerUi, {
theme: {
css: [
{ filename: 'theme.css', content: '* {border: 1px red solid;}' }
]
}
})
const res = await fastify.inject({
method: 'GET',
url: '/documentation'
})
t.equal(typeof res.payload, 'string')
t.match(res.payload, /theme\/theme\.css/)
t.equal(res.headers['content-type'], 'text/html; charset=utf-8')
{
const res = await fastify.inject({
method: 'GET',
url: '/documentation/static/theme/theme.css'
})
t.equal(res.payload, '* {border: 1px red solid;}')
}
})
test('swagger route returns additional theme - only favicon', async (t) => {
const config = {
mode: 'static',
specification: {
path: './examples/example-static-specification.yaml'
}
}
t.plan(5)
const fastify = Fastify()
await fastify.register(fastifySwagger, config)
await fastify.register(fastifySwaggerUi, {
theme: {
favicon: [
{
filename: 'favicon.png',
rel: 'icon',
sizes: '16x16',
type: 'image/png',
content: Buffer.from('iVBORw0KGgoAAAANSUhEUgAAAA8AAAAQCAQAAABjX+2PAAAAIGNIUk0AAHomAACAhAAA+gAAAIDoAAB1MAAA6mAAADqYAAAXcJy6UTwAAAACYktHRAD/h4/MvwAAAAd0SU1FB+cCEQ06N8A8CiUAAADnSURBVBjTrdE/K8QBAMbxz/0TLrnUWcTg7ySLewGEwWDRzSYpyULJbGG6wWBTlMEbkHsFNnVloAwXudIlnDru1O9nOCex3rM89TzL0/eh1Ypo//Zk5CdM6JP2IWFOxbmMKZVmPWzbrJSamG5FNXUFx42yV16oqCQUerNr2pghsSgS1sw4kxNVVvbu3rwjSwJ67Kgq2XMjtO/AnWsnVgwQNy6rQ8GkURWBpCebXnR5gA11j5b1OxT4EKq6dGurMWvQqqw2LPoUKDq1LqPzN4q0rCuvckbE/pOakHdhQfwvwKan8Nzad74AkR8/Ir6qAvAAAAAldEVYdGRhdGU6Y3JlYXRlADIwMjMtMDItMTdUMTM6NTg6NTUrMDA6MDBjkr64AAAAJXRFWHRkYXRlOm1vZGlmeQAyMDIzLTAyLTE3VDEzOjU4OjU1KzAwOjAwEs8GBAAAACh0RVh0ZGF0ZTp0aW1lc3RhbXAAMjAyMy0wMi0xN1QxMzo1ODo1NSswMDowMEXaJ9sAAAAASUVORK5CYII=', 'base64')
}
]
}
})
const res = await fastify.inject({
method: 'GET',
url: '/documentation'
})
t.equal(typeof res.payload, 'string')
t.match(res.payload, /theme\/favicon\.png/)
t.equal(res.headers['content-type'], 'text/html; charset=utf-8')
{
const res = await fastify.inject({
method: 'GET',
url: '/documentation/static/theme/favicon.png'
})
t.equal(res.statusCode, 200)
t.equal(res.headers['content-type'], 'image/png')
}
})
test('swagger route returns additional theme - only title', async (t) => {
const config = {
mode: 'static',
specification: {
path: './examples/example-static-specification.yaml'
}
}
t.plan(3)
const fastify = Fastify()
await fastify.register(fastifySwagger, config)
await fastify.register(fastifySwaggerUi, {
theme: {
title: 'My custom title'
}
})
const res = await fastify.inject({
method: 'GET',
url: '/documentation'
})
t.equal(typeof res.payload, 'string')
t.match(res.payload, /<title>My custom title<\/title>/)
t.equal(res.headers['content-type'], 'text/html; charset=utf-8')
})

View File

@@ -0,0 +1,269 @@
'use strict'
const { test } = require('tap')
const Fastify = require('fastify')
const fastifySwagger = require('@fastify/swagger')
const fastifySwaggerUi = require('../index')
const yaml = require('yaml')
test('transformSpecification should modify the json', async (t) => {
t.plan(5)
const fastify = Fastify()
await fastify.register(fastifySwagger, {
swagger: {
info: {
title: 'Test swagger',
description: 'Testing the Fastify swagger API',
version: '0.1.0'
},
externalDocs: {
url: 'https://swagger.io',
description: 'Find more info here'
},
host: 'localhost',
schemes: ['http'],
consumes: ['application/json'],
produces: ['application/json'],
tags: [
{ name: 'user', description: 'User related end-points' },
{ name: 'code', description: 'Code related end-points' }
],
definitions: {
User: {
type: 'object',
required: ['id', 'email'],
properties: {
id: { type: 'string', format: 'uuid' },
firstName: { type: 'string' },
lastName: { type: 'string' },
email: { type: 'string', format: 'email' }
}
}
},
securityDefinitions: {
apiKey: {
type: 'apiKey',
name: 'apiKey',
in: 'header'
}
}
}
})
await fastify.register(fastifySwaggerUi, {
transformSpecification: function (swaggerObject, req, reply) {
t.not(swaggerObject, fastify.swagger())
t.ok(req)
t.ok(reply)
swaggerObject.swagger = '2.1'
return swaggerObject
}
})
await fastify.ready()
const res = await fastify.inject({
method: 'GET',
url: '/documentation/json'
})
t.notSame(fastify.swagger(), JSON.parse(res.body))
t.equal(JSON.parse(res.body).swagger, '2.1')
})
test('transformSpecificationClone false should not deepclone fastify.swagger() /1', async (t) => {
t.plan(4)
const fastify = Fastify()
await fastify.register(fastifySwagger, {
swagger: {
info: {
title: 'Test swagger',
description: 'Testing the Fastify swagger API',
version: '0.1.0'
},
externalDocs: {
url: 'https://swagger.io',
description: 'Find more info here'
},
host: 'localhost',
schemes: ['http'],
consumes: ['application/json'],
produces: ['application/json'],
tags: [
{ name: 'user', description: 'User related end-points' },
{ name: 'code', description: 'Code related end-points' }
],
definitions: {
User: {
type: 'object',
required: ['id', 'email'],
properties: {
id: { type: 'string', format: 'uuid' },
firstName: { type: 'string' },
lastName: { type: 'string' },
email: { type: 'string', format: 'email' }
}
}
},
securityDefinitions: {
apiKey: {
type: 'apiKey',
name: 'apiKey',
in: 'header'
}
}
}
})
await fastify.register(fastifySwaggerUi, {
transformSpecificationClone: false,
transformSpecification: function (swaggerObject, req, reply) {
t.equal(swaggerObject, fastify.swagger())
t.ok(req)
t.ok(reply)
return swaggerObject
}
})
await fastify.ready()
const res = await fastify.inject({
method: 'GET',
url: '/documentation/json'
})
const swagger = fastify.swagger()
Object.getOwnPropertySymbols(swagger.definitions.User).forEach((symbol) => delete swagger.definitions.User[symbol])
t.strictSame(swagger, JSON.parse(res.body))
})
test('transformSpecification should modify the yaml', async (t) => {
t.plan(4)
const fastify = Fastify()
await fastify.register(fastifySwagger, {
swagger: {
info: {
title: 'Test swagger',
description: 'Testing the Fastify swagger API',
version: '0.1.0'
},
externalDocs: {
url: 'https://swagger.io',
description: 'Find more info here'
},
host: 'localhost',
schemes: ['http'],
consumes: ['application/json'],
produces: ['application/json'],
tags: [
{ name: 'user', description: 'User related end-points' },
{ name: 'code', description: 'Code related end-points' }
],
definitions: {
User: {
type: 'object',
required: ['id', 'email'],
properties: {
id: { type: 'string', format: 'uuid' },
firstName: { type: 'string' },
lastName: { type: 'string' },
email: { type: 'string', format: 'email' }
}
}
},
securityDefinitions: {
apiKey: {
type: 'apiKey',
name: 'apiKey',
in: 'header'
}
}
}
})
await fastify.register(fastifySwaggerUi, {
transformSpecification: function (swaggerObject, req, reply) {
swaggerObject.swagger = '2.1'
t.ok(req)
t.ok(reply)
return swaggerObject
}
})
await fastify.ready()
const swaggerPre = fastify.swagger()
const res = await fastify.inject({
method: 'GET',
url: '/documentation/yaml'
})
t.same(fastify.swagger(), swaggerPre)
t.equal(yaml.parse(res.body).swagger, '2.1')
})
test('transformSpecificationClone false should not deepclone fastify.swagger() /2', async (t) => {
t.plan(4)
const fastify = Fastify()
await fastify.register(fastifySwagger, {
swagger: {
info: {
title: 'Test swagger',
description: 'Testing the Fastify swagger API',
version: '0.1.0'
},
externalDocs: {
url: 'https://swagger.io',
description: 'Find more info here'
},
host: 'localhost',
schemes: ['http'],
consumes: ['application/json'],
produces: ['application/json'],
tags: [
{ name: 'user', description: 'User related end-points' },
{ name: 'code', description: 'Code related end-points' }
],
definitions: {
User: {
type: 'object',
required: ['id', 'email'],
properties: {
id: { type: 'string', format: 'uuid' },
firstName: { type: 'string' },
lastName: { type: 'string' },
email: { type: 'string', format: 'email' }
}
}
},
securityDefinitions: {
apiKey: {
type: 'apiKey',
name: 'apiKey',
in: 'header'
}
}
}
})
await fastify.register(fastifySwaggerUi, {
transformSpecificationClone: false,
transformSpecification: function (swaggerObject, req, reply) {
t.equal(swaggerObject, fastify.swagger())
t.ok(req)
t.ok(reply)
return swaggerObject
}
})
await fastify.ready()
const swaggerPre = fastify.swagger()
await fastify.inject({
method: 'GET',
url: '/documentation/yaml'
})
t.same(fastify.swagger(), swaggerPre)
})