UNPKG

nestjs-inertia

Version:

Unofficial NestJS (express platform) adapter for InertiaJS.

90 lines 2.95 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); const template_1 = require("./template"); class Inertia { constructor(req, res, version = '1') { this.version = null; this.sharedProps = {}; this.version = version; this.req = req; this.res = res; } checkVersion() { if (this.req.method === 'GET' && this.req.headers['x-inertia'] && this.req.headers['x-inertia-version'] !== this.version) { this.res.writeHead(409, { 'X-Inertia-Location': this.req.url }).end(); return false; } return true; } flushShared() { this.sharedProps = {}; } getShared(key, defaultKey) { var _a; if (key) { return (_a = this.sharedProps[key]) !== null && _a !== void 0 ? _a : this.sharedProps[defaultKey]; } return this.sharedProps; } getVersion() { return this.version; } location(url) { this.res.writeHead(409, { 'X-Inertia-Location': url }).end(); } share(props) { this.sharedProps = Object.assign(Object.assign({}, this.sharedProps), props); } async render(component = this.component, props) { let page = { component, props: {}, url: this.req.originalUrl || this.req.url, version: this.version }; const allProps = Object.assign(Object.assign({}, this.sharedProps), props); let dataKeys; if (this.req.headers['x-inertia-partial-data'] && this.req.headers['x-inertia-partial-component'] === component) { dataKeys = this.req.headers['x-inertia-partial-data'].split(','); } else { dataKeys = Object.keys(allProps); } for (const key of dataKeys) { if (typeof allProps[key] === 'function') { page.props[key] = await allProps[key](); } else { page.props[key] = allProps[key]; } } if (this.req.headers['x-inertia']) { this.res.writeHead(200, { Vary: 'Accept', 'X-Inertia': 'true', 'Content-Type': 'application/json', }) .end(JSON.stringify(page)); } else { const encodedPageString = JSON.stringify(page) .replace(/'/g, '"') .replace(/'/g, '''); this.res.writeHead(200, { 'Content-Type': 'text/html', }) .end((0, template_1.default)(encodedPageString)); } } redirect(url) { const statusCode = ['PUT', 'PATCH', 'DELETE'].includes(this.req.method) ? 303 : 302; this.res.writeHead(statusCode, { Location: url }).end(); } } exports.default = Inertia; //# sourceMappingURL=inertia.js.map