Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
// validate openapi and warn in case there are issues
const { valid, errors } = validate(apispec, 3);
if (valid) {
console.info('\x1b[32m[success]\x1b[0m Document is valid OpenAPI v3!');
} else {
console.warn(`\x1b[33m[warning]\x1b[0m Document is not valid OpenAPI!\n ${errors.length} validation errors:\n` +
JSON.stringify(errors, null, 2));
}
// write to swagger.json file under static/
const swaggerFile = path.join(outputPath, 'swagger.json');
fs.writeFileSync(swaggerFile, JSON.stringify(apispec));
console.info(`[info] Wrote OpenAPI spec to ${path.basename(outputPath)}/${path.basename(swaggerFile)}`);
// copy swagger ui dist files
const swaggerDist = getAbsoluteFSPath();
const swaggerFiles = fs.readdirSync(swaggerDist)
.filter(file => !file.endsWith('.map'));
for (const file of swaggerFiles) {
const source = path.join(swaggerDist, file);
const target = path.join(outputPath, file);
fs.writeFileSync(target, fs.readFileSync(source));
}
console.info(`[info] Copied ${swaggerFiles.length} SwaggerUI files to ${path.basename(outputPath)}/`);
// replace api url to relative ./swagger.json in index.html
const index = fs.readFileSync(path.join(swaggerDist, 'index.html'));
const replaced = index.toString()
.replace(new RegExp('https://petstore.swagger.io/v2/swagger.json', 'g'), './swagger.json')
.replace(new RegExp('http://example.com/api', 'g'), './swagger.json')
fs.writeFileSync(path.join(outputPath, 'index.html'), replaced);
console.info(`[info] Replaced index.html swagger url with relative swagger.json`);
import * as URL from 'url';
import * as fs from 'fs';
import * as path from 'path';
import * as Koa from 'koa';
import * as Router from 'koa-router';
import * as serve from 'koa-static';
import * as SwaggerUIDist from 'swagger-ui-dist';
import { Document } from 'swagger-parser';
export const swaggerUIRoot = SwaggerUIDist.getAbsoluteFSPath();
export enum DocExpansion {
Full = 'full', // expand averything
List = 'list', // expand only only tags
None = 'none', // expand nothing
}
export interface SwaggerUIOpts {
url?: string; // remote URL
spec?: Document; // use a definition object instead of URL
deepLinking?: boolean; // allow deep linking
docExpansion?: DocExpansion; // default expansion setting for the operations and tags
displayOperationId?: boolean; // display operationIds
displayRequestDuration?: boolean; // display request durations in "try it out"
showExtensions?: boolean; // display extensions
showCommonExtensions?: boolean; // display common extensions
var userId = Math.ceil(Math.random() * mockUserBasicInfo.length);
request.setResourceId('/users/' + userId);
return request;
});
/*** Set up some aliases ***/
api.alias('/me', function(request, connection) {
request.setResourceId('/users/2');
return request;
});
// Allow uploaded files to be served
var serveStatic = require('serve-static');
app.use(serveStatic(path.join(__dirname, 'files')));
var swagger = require('swagger-ui-dist').getAbsoluteFSPath();
app.use("/swagger", chain(
function(req, res, next) {
if(req.method === "GET" && req.url === '/') {
res.writeHead(302, {'location': '?url=http://localhost:5150/my-api'});
return res.end();
}
next();
},
serveStatic(swagger)
));
// Mount the API as middleware
app.use(api.middleware({
basePath: '/my-api'
}));
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
* either express or implied. See the License for the specific
* language governing permissions and limitations under the License.
*/
var config = require('./config/config');
var _ = require('lodash'),
fs = require('fs'),
express = require('express'),
morgan = require('morgan'),
errorHandler = require('errorhandler'),
bodyParser = require('body-parser'),
compression = require('compression'),
serveStatic = require('serve-static'),
swaggerUiAssetPath = require("swagger-ui-dist").getAbsoluteFSPath();
var mongo = require('./mongo');
var app = module.exports = express();
app.enable('trust proxy');
app.set('port', process.env.PORT || config.port);
app.use(morgan('combined'));
app.use(compression());
/* Support for non-Unicode charsets (e.g. ISO-8859-1) */
app.use(bodyParser.text({
type: '*/*',
limit: (config.requestLimit || '1mb')
}));
const Hoek = require('@hapi/hoek');
const Joi = require('@hapi/joi');
const Path = require('path');
const { join, sep } = require('path');
const Querystring = require('querystring');
const Url = require('url');
const swaggerUiAssetPath = require('swagger-ui-dist').getAbsoluteFSPath();
const Pack = require('../package.json');
const Defaults = require('../lib/defaults');
const Builder = require('../lib/builder');
const Utilities = require('../lib/utilities');
// schema for plug-in properties
const schema = Joi.object({
debug: Joi.boolean(),
jsonPath: Joi.string(),
documentationPath: Joi.string(),
documentationRouteTags: Joi.alternatives().try(Joi.string(), Joi.array().items(Joi.string())),
templates: Joi.string(),
swaggerUIPath: Joi.string(),
auth: Joi.alternatives().try(Joi.boolean(), Joi.string(), Joi.object()),
pathPrefixSize: Joi.number()
swaggerUiStandalonePreset() {
return createHttpResponseFile({
directory: getAbsoluteFSPath(),
file: 'swagger-ui-standalone-preset.js'
});
}
import * as express from 'express'
import * as bodyParser from 'body-parser'
import { RegisterRoutes } from './routes'
import './controllers/smart-contract'
import { ExecutionEngineConfig } from './config'
const swaggerUiAssetPath = require('swagger-ui-dist').getAbsoluteFSPath()
export function configureApi () {
const app = express()
app.use(bodyParser.json({ limit: '50mb' }))
app.use('/documentation', express.static(swaggerUiAssetPath))
app.use('/documentation/swagger.json', (_, res) => {
res.sendFile(process.cwd() + '/dist/swagger.json')
})
app.get('/docs', (_, res) => {
res.redirect('/documentation?url=swagger.json')
})
RegisterRoutes(app)
app.use(function (_req, res, _next) {
async execute(invocation: Readonly): Promise {
const uiPath = this.opt.endpoint.toLowerCase() + "/index"
if (invocation.context.path.toLowerCase() === "/swagger.json")
return response.json(this.spec)
if (invocation.context.path.toLowerCase() === this.opt.endpoint.toLowerCase())
return response.redirect(uiPath)
if (invocation.context.path.toLowerCase() === uiPath)
return response.file(join(dist.getAbsoluteFSPath(), "index.html"))
else
return invocation.proceed()
}
}
strapi.router.get('/plugins/documentation/*', async (ctx, next) => {
ctx.url = path.basename(ctx.url);
return await koaStatic(swaggerUi.getAbsoluteFSPath(), {
maxage: strapi.config.middleware.settings.public.maxAge,
defer: true,
})(ctx, next);
});
},
async initialize(app: Readonly, routes: RouteInfo[]): Promise {
const path = dist.getAbsoluteFSPath()
const spec = transform(routes)
app.use(new OpenApiMiddleware(spec, this.opt))
app.use(new ServeStaticMiddleware({ root: path, rootPath: this.opt.endpoint }))
}
}