Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: use formater #198

Closed
wants to merge 1 commit into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions .travis.yml
Original file line number Diff line number Diff line change
Expand Up @@ -8,3 +8,4 @@ branches:
script:
- "npm run cover"
- "npm run lint"
- "npm run format-check"
6 changes: 3 additions & 3 deletions lib/caller.js
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
'use strict';
"use strict";

/*
* Copy of Erik's caller module with node 8 support added.
*/
*/

/**
* Module wrapper of @substack's `caller.js`
Expand All @@ -23,7 +23,7 @@ const caller = function (depth) {
return stack;
};

const stack = (new Error()).stack.slice(2);
const stack = new Error().stack.slice(2);

let file;

Expand Down
131 changes: 78 additions & 53 deletions lib/index.js
Original file line number Diff line number Diff line change
@@ -1,34 +1,39 @@
'use strict';

const Package = require('../package.json');
const Joi = require('joi');
const Hoek = require('@hapi/hoek');
const Caller = require('./caller');
const Path = require('path');
const Parser = require('swagger-parser');
const Utils = require('./utils');
const Routes = require('./routes');
const Yaml = require('js-yaml');
const Fs = require('fs');
const Util = require('util');
"use strict";

const Package = require("../package.json");
const Joi = require("joi");
const Hoek = require("@hapi/hoek");
const Caller = require("./caller");
const Path = require("path");
const Parser = require("swagger-parser");
const Utils = require("./utils");
const Routes = require("./routes");
const Yaml = require("js-yaml");
const Fs = require("fs");
const Util = require("util");

const CALLER_DIR = Path.resolve(Path.dirname(Caller()));

const optionsSchema = Joi.object({
api: Joi.alternatives(Joi.string(), Joi.object().unknown(true)),
//deprecated
docspath: Joi.string().default('/api-docs'),
docspath: Joi.string().default("/api-docs"),
docs: Joi.object({
path: Joi.string().default('/api-docs'),
path: Joi.string().default("/api-docs"),
auth: Joi.alternatives().try(Joi.object(), Joi.boolean()).allow(null),
stripExtensions: Joi.boolean().default(true),
prefixBasePath: Joi.boolean().default(true)
prefixBasePath: Joi.boolean().default(true),
}).default(),
cors: Joi.alternatives().try(Joi.object(), Joi.boolean()).default(true),
vhost: Joi.string().allow(null),
handlers: Joi.alternatives().try(Joi.string().default(Path.join(CALLER_DIR, 'routes')), Joi.object()).allow(null),
extensions: Joi.array().items(Joi.string()).default(['js']),
outputvalidation: Joi.boolean().default(false)
handlers: Joi.alternatives()
.try(
Joi.string().default(Path.join(CALLER_DIR, "routes")),
Joi.object()
)
.allow(null),
extensions: Joi.array().items(Joi.string()).default(["js"]),
outputvalidation: Joi.boolean().default(false),
}).required();

const stripVendorExtensions = function (obj) {
Expand Down Expand Up @@ -61,33 +66,37 @@ const requireApi = function (path) {
if (path.match(/\.ya?ml?/)) {
const file = Fs.readFileSync(path);
document = Yaml.load(file);
}
else {
} else {
document = require(path);
}

return document;
};

const register = async function (server, options, next) {

//Validator needs to be explicitly declared for Hapi v19.*
server.validator(require('joi'));
server.validator(require("joi"));

const validation = optionsSchema.validate(options);

Hoek.assert(!validation.error, validation.error);

const { api, cors, vhost, handlers, extensions, outputvalidation } = validation.value;
const { api, cors, vhost, handlers, extensions, outputvalidation } =
validation.value;
let { docs, docspath } = validation.value;
const spec = await Parser.validate(api);

// Cannot use conflicting url pathnames, so opting to mount the first url pathname
if (spec.openapi) {
spec.basePath = new URL(Hoek.reach(spec, ['servers', 0, 'url'])).pathname;
spec.basePath = new URL(
Hoek.reach(spec, ["servers", 0, "url"])
).pathname;
}

spec.basePath = Utils.unsuffix(Utils.prefix(spec.basePath || '/', '/'), '/');
spec.basePath = Utils.unsuffix(
Utils.prefix(spec.basePath || "/", "/"),
"/"
);

//Expose plugin api
server.expose({
Expand All @@ -96,36 +105,37 @@ const register = async function (server, options, next) {
},
setHost: function setHost(host) {
spec.host = host;
}
},
});

let basedir;
let apiDocument;

if (typeof api === 'string') {
if (typeof api === "string") {
apiDocument = requireApi(api);
basedir = Path.dirname(Path.resolve(api));
}
else {
} else {
apiDocument = api;
basedir = CALLER_DIR;
}

if (spec['x-hapi-auth-schemes']) {
for (const [name, path] of Object.entries(spec['x-hapi-auth-schemes'])) {
if (spec["x-hapi-auth-schemes"]) {
for (const [name, path] of Object.entries(
spec["x-hapi-auth-schemes"]
)) {
const scheme = require(Path.resolve(Path.join(basedir, path)));

await server.register({
plugin: scheme,
options: {
name
}
name,
},
});
}
}

let securitySchemes;

if (spec.swagger && spec.securityDefinitions) {
securitySchemes = spec.securityDefinitions;
}
Expand All @@ -136,34 +146,36 @@ const register = async function (server, options, next) {

if (securitySchemes) {
for (const [name, security] of Object.entries(securitySchemes)) {
if (security['x-hapi-auth-strategy']) {
const strategy = require(Path.resolve(Path.join(basedir, security['x-hapi-auth-strategy'])));
if (security["x-hapi-auth-strategy"]) {
const strategy = require(Path.resolve(
Path.join(basedir, security["x-hapi-auth-strategy"])
));

await server.register({
plugin: strategy,
options: {
name,
scheme: security.type,
lookup: security.name,
where: security.in
}
where: security.in,
},
});
}
}
}

if (docspath !== '/api-docs' && docs.path === '/api-docs') {
server.log(['warn'], 'docspath is deprecated. Use docs instead.');
if (docspath !== "/api-docs" && docs.path === "/api-docs") {
server.log(["warn"], "docspath is deprecated. Use docs instead.");
docs = {
path: docspath,
prefixBasePath: docs.prefixBasePath
prefixBasePath: docs.prefixBasePath,
};
}

let apiPath = docs.path;
if (docs.prefixBasePath){
docs.path = Utils.prefix(docs.path, '/');
docs.path = Utils.unsuffix(docs.path, '/');
if (docs.prefixBasePath) {
docs.path = Utils.prefix(docs.path, "/");
docs.path = Utils.unsuffix(docs.path, "/");
apiPath = spec.basePath + docs.path;
}

Expand All @@ -173,26 +185,39 @@ const register = async function (server, options, next) {

//API docs route
server.route({
method: 'GET',
method: "GET",
path: apiPath,
config: {
handler(request, h) {
return apiDocument;
},
cors,
id: `${apiPath.replace(/\//g, '_')}`,
description: 'The OpenAPI document.',
tags: ['api', 'documentation'],
auth: docs.auth
id: `${apiPath.replace(/\//g, "_")}`,
description: "The OpenAPI document.",
tags: ["api", "documentation"],
auth: docs.auth,
},
vhost
vhost,
});

const routes = await Routes.create(server, { api: spec, basedir, cors, vhost, handlers, extensions, outputvalidation });
const routes = await Routes.create(server, {
api: spec,
basedir,
cors,
vhost,
handlers,
extensions,
outputvalidation,
});

for (const route of routes) {
server.route(route);
}
};

module.exports.plugin = { register, name: 'openapi', version: Package.version, multiple: true };
module.exports.plugin = {
register,
name: "openapi",
version: Package.version,
multiple: true,
};
Loading