UNPKG

@nestjs/platform-fastify

Version:

Nest - modern, fast, powerful node.js web framework (@platform-fastify)

175 lines (174 loc) 6.01 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.FastifyAdapter = void 0; /* eslint-disable @typescript-eslint/no-var-requires */ const common_1 = require("@nestjs/common"); const load_package_util_1 = require("@nestjs/common/utils/load-package.util"); const http_adapter_1 = require("@nestjs/core/adapters/http-adapter"); const fastify_1 = require("fastify"); const Reply = require("fastify/lib/reply"); const pathToRegexp = require("path-to-regexp"); class FastifyAdapter extends http_adapter_1.AbstractHttpAdapter { constructor(instanceOrOptions = fastify_1.fastify()) { const instance = instanceOrOptions && instanceOrOptions.server ? instanceOrOptions : fastify_1.fastify(instanceOrOptions); super(instance); } get isParserRegistered() { return !!this._isParserRegistered; } async init() { if (this.isMiddieRegistered) { return; } await this.registerMiddie(); } listen(port, ...args) { return this.instance.listen(port, ...args); } reply(response, body, statusCode) { const fastifyReply = this.isNativeResponse(response) ? new Reply(response, { context: { preSerialization: null, preValidation: [], preHandler: [], onSend: [], onError: [], }, }, {}) : response; if (statusCode) { fastifyReply.status(statusCode); } return fastifyReply.send(body); } status(response, statusCode) { if (this.isNativeResponse(response)) { response.statusCode = statusCode; return response; } return response.code(statusCode); } render(response, view, options) { return response && response.view(view, options); } redirect(response, statusCode, url) { const code = statusCode !== null && statusCode !== void 0 ? statusCode : common_1.HttpStatus.FOUND; return response.status(code).redirect(url); } setErrorHandler(handler) { return this.instance.setErrorHandler(handler); } setNotFoundHandler(handler) { return this.instance.setNotFoundHandler(handler); } getHttpServer() { return this.instance.server; } getInstance() { return this.instance; } register(plugin, opts) { return this.instance.register(plugin, opts); } inject(opts) { return this.instance.inject(opts); } async close() { try { return await this.instance.close(); } catch (err) { // Check if server is still running if (err.code !== 'ERR_SERVER_NOT_RUNNING') { throw err; } return; } } initHttpServer() { this.httpServer = this.instance.server; } useStaticAssets(options) { return this.register(load_package_util_1.loadPackage('fastify-static', 'FastifyAdapter.useStaticAssets()'), options); } setViewEngine(options) { if (typeof options === 'string') { new common_1.Logger('FastifyAdapter').error("setViewEngine() doesn't support a string argument."); process.exit(1); } return this.register(load_package_util_1.loadPackage('point-of-view', 'FastifyAdapter.setViewEngine()'), options); } setHeader(response, name, value) { return response.header(name, value); } getRequestHostname(request) { return request.hostname; } getRequestMethod(request) { return request.raw ? request.raw.method : request.method; } getRequestUrl(request) { return request.raw ? request.raw.url : request.url; } enableCors(options) { if (typeof options === 'function') { this.register(require('fastify-cors'), () => options); } else { this.register(require('fastify-cors'), options); } } registerParserMiddleware() { if (this._isParserRegistered) { return; } this.register(require('fastify-formbody')); this._isParserRegistered = true; } async createMiddlewareFactory(requestMethod) { if (!this.isMiddieRegistered) { await this.registerMiddie(); } return (path, callback) => { const re = pathToRegexp(path); const normalizedPath = path === '/*' ? '' : path; // The following type assertion is valid as we enforce "middie" plugin registration // which enhances the FastifyInstance with the "use()" method. // ref https://github.com/fastify/middie/pull/55 const instanceWithUseFn = this .instance; instanceWithUseFn.use(normalizedPath, (req, res, next) => { const queryParamsIndex = req.originalUrl.indexOf('?'); const pathname = queryParamsIndex >= 0 ? req.originalUrl.slice(0, queryParamsIndex) : req.originalUrl; if (!re.exec(pathname + '/') && normalizedPath) { return next(); } if (requestMethod === common_1.RequestMethod.ALL || req.method === common_1.RequestMethod[requestMethod]) { return callback(req, res, next); } next(); }); }; } getType() { return 'fastify'; } registerWithPrefix(factory, prefix = '/') { return this.instance.register(factory, { prefix }); } isNativeResponse(response) { return !('status' in response); } async registerMiddie() { this.isMiddieRegistered = true; await this.register(require('middie')); } } exports.FastifyAdapter = FastifyAdapter;