@oada/well-known-json
Version:
Middleware for JSON Well-Known resources
72 lines • 3.18 kB
JavaScript
;
/**
* @license
* Copyright 2014-2022 Open Ag Data Alliance
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "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.
*/
Object.defineProperty(exports, "__esModule", { value: true });
exports.wellKnownJSON = void 0;
const tslib_1 = require("tslib");
const node_util_1 = tslib_1.__importDefault(require("node:util"));
const allow_methods_1 = tslib_1.__importDefault(require("allow-methods"));
const cors_1 = tslib_1.__importDefault(require("cors"));
const WellKnownJSON_js_1 = require("./WellKnownJSON.js");
const WELL_KNOWN = /^\/\.well-known\/(.*)/;
const METHODS = ['OPTIONS', 'GET', 'HEAD'];
function wellKnownJSON(resources, options = {}) {
const wkj = new WellKnownJSON_js_1.WellKnownJSON(resources, options);
const c = options.cors ?? {};
const corsOptions = typeof c === 'function'
? function (request, callback) {
c(request, (error, opt) => {
callback(error, { methods: METHODS, ...opt });
});
}
: { methods: METHODS, ...c };
const allowMiddleware = node_util_1.default.promisify((0, allow_methods_1.default)(options.methods ?? METHODS));
const corsMiddleware = node_util_1.default.promisify((0, cors_1.default)(corsOptions));
const middleware = (request, response, next) => {
async function handler() {
const m = WELL_KNOWN.exec(request.path);
const base = `${options.forceProtocol ??
request.headers['x-forwarded-proto'] ??
request.protocol}://${request.headers['x-forwarded-host'] ?? request.headers.host}`;
const match = m?.[1] && wkj.getResource(m[1], base, request, response);
if (match === undefined) {
// Pass to next middleware
return;
}
await allowMiddleware(request, response);
await corsMiddleware(request, response);
if (!request.accepts('json')) {
return response.status(406).send('Not Acceptable');
}
if (options.headers) {
response.set(options.headers);
}
return response.json(match);
}
handler()
// eslint-disable-next-line github/no-then, promise/always-return
.then(() => {
// eslint-disable-next-line promise/no-callback-in-promise
next();
})
// eslint-disable-next-line github/no-then, promise/no-callback-in-promise
.catch(next);
};
return Object.assign(middleware, { addResource: wkj.addResource.bind(wkj) });
}
exports.wellKnownJSON = wellKnownJSON;
//# sourceMappingURL=middleware.js.map