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 routes from './routes';
import json from './middlewares/json';
import logger, { logStream } from './utils/logger';
import * as errorHandler from './middlewares/errorHandler';
// Initialize Sentry
// https://docs.sentry.io/platforms/node/express/
Sentry.init({ dsn: process.env.SENTRY_DSN });
const app = express();
const APP_PORT =
(process.env.NODE_ENV === 'test' ? process.env.TEST_APP_PORT : process.env.APP_PORT) || process.env.PORT || '3000';
const APP_HOST = process.env.APP_HOST || '0.0.0.0';
const pathToSwaggerUi = require('swagger-ui-dist').absolutePath();
app.set('port', APP_PORT);
app.set('host', APP_HOST);
app.locals.title = process.env.APP_NAME;
app.locals.version = process.env.APP_VERSION;
// This request handler must be the first middleware on the app
app.use(Sentry.Handlers.requestHandler());
app.use(favicon(path.join(__dirname, '/../public', 'favicon.ico')));
app.use(cors());
app.use(helmet());
app.use(compression());
app.use(morgan('tiny', { stream: logStream }));
app.use(bodyParser.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()
import * as path from 'path';
import * as fs from 'fs';
import * as url from 'url';
import * as Koa from 'koa';
import * as send from 'koa-send';
// tslint:disable-next-line
const swaggerUIAbsolutePath = require('swagger-ui-dist').absolutePath();
import config from '../config';
export default () => {
const swaggerIndex = fs
.readFileSync(path.join(swaggerUIAbsolutePath, 'index.html'), { encoding: 'utf8' })
.replace('https://petstore.swagger.io/v2/swagger.json', url.resolve(config.BACKEND_URL, 'spec'));
return async (ctx: Koa.Context, next: () => Promise) => {
if (ctx.path.match(/^\/swagger\/.*$/)) {
const _path = ctx.path.replace('/swagger/', '');
if (_path === '' || _path === '/index.html') {
ctx.body = swaggerIndex;
return;
}
await send(ctx, _path, { root: swaggerUIAbsolutePath });
} else {
created() {
const route = _.defaultsDeep(mixinOptions.routeOptions, {
use: [
ApiGateway.serveStatic(SwaggerUI.absolutePath())
],
aliases: {
"GET /openapi.json"(req, res) {
// Send back the generated schema
if (shouldUpdateSchema || !schema) {
// Create new server & regenerate GraphQL schema
this.logger.info("♻ Regenerate OpenAPI/Swagger schema...");
try {
schema = this.generateOpenAPISchema();
shouldUpdateSchema = false;
this.logger.debug(schema);
export const command: Command = async() => {
log(LogCategory.Progress, 'Starting the API browser...');
const app = express();
// Add backend proxy
backendEndpoints.forEach(path => app.use(path, backend));
// Add index page
app.get(['/', '/index.html'], (_: Request, res: Response) => {
res.send(renderOpenApiHtml());
});
// Add static resources
const pathToSwaggerUi = require('swagger-ui-dist').absolutePath();
app.use(express.static(pathToSwaggerUi));
// Start the server
const server = require('http').createServer(app);
const listen = util.promisify(server.listen);
await listen.call(server, CONNECT_API_PORT, CONNECT_API_HOSTNAME);
// Log the started server url
const {address, port} = server.address();
const hostname = CONNECT_API_HOSTNAME || address;
const url = new URL(`http://${hostname}:${port}`);
log(LogCategory.Success, `The API browser is running at: ${url}`);
return () => {
log(LogCategory.Progress, 'Stopping the API browser...');
// Cleanup
const config_1 = require("./config");
const fs = require("fs");
const url = require("url");
const path = require("path");
const knex = require("knex");
const Koa = require("koa");
const bodyParser = require("koa-bodyparser");
const cors = require("kcors");
const send = require("koa-send");
const Router = require("koa-router");
const objection_1 = require("objection");
objection_1.Model.knex(knex(config_1.default.DATABASE));
const jwt = require("jsonwebtoken");
const yaml = require("yamljs");
// tslint:disable-next-line
const swaggerUIAbsolutePath = require('swagger-ui-dist').absolutePath();
const routes_1 = require("./authentication/jwt/routes");
const middleware_1 = require("./authentication/jwt/middleware");
const ProjectViewSet_1 = require("./viewsets/ProjectViewSet");
const UserViewSet_1 = require("./viewsets/UserViewSet");
const ClientViewSet_1 = require("./viewsets/ClientViewSet");
const WebHookViewSet_1 = require("./viewsets/WebHookViewSet");
const ProjectInviteViewSet_1 = require("./viewsets/ProjectInviteViewSet");
const MediaViewSet_1 = require("./viewsets/MediaViewSet");
const MediaTagViewSet_1 = require("./viewsets/MediaTagViewSet");
const EntryTypeViewSet_1 = require("./viewsets/EntryTypeViewSet");
const EntryViewSet_1 = require("./viewsets/EntryViewSet");
const EntryTagViewSet_1 = require("./viewsets/EntryTagViewSet");
const Client_1 = require("./models/Client");
const Entry_1 = require("./models/Entry");
const EntryTag_1 = require("./models/EntryTag");
const EntryType_1 = require("./models/EntryType");