Skip to content

Commit

Permalink
Add in allRequests boolean on server
Browse files Browse the repository at this point in the history
  • Loading branch information
nickreese committed May 18, 2022
1 parent c3c4cfd commit 0902435
Show file tree
Hide file tree
Showing 7 changed files with 81 additions and 15 deletions.
2 changes: 1 addition & 1 deletion package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "@elderjs/elderjs",
"version": "1.7.1",
"version": "1.7.2",
"main": "./build/index.js",
"types": "./build/index.d.ts",
"engineStrict": true,
Expand Down
52 changes: 40 additions & 12 deletions src/routes/prepareRouter.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
import routeSort from 'route-sort';
import get from 'lodash.get';
import Page from '../utils/Page';
import { RequestOptions } from '../utils/types';
import { RequestOptions, ServerOptions } from '../utils/types';
import { RouteOptions } from './types';

export function extractDynamicRouteParams({ path, $$meta }) {
Expand Down Expand Up @@ -36,30 +36,48 @@ type Req = {
search?: string;
};

interface IFindPrebuildRequest {
interface IGetSpecialRequest {
req: Req;
serverLookupObject: any;
dataRoutes: boolean | string;
server: ServerOptions;
}

export const getDataRequest = ({ req, server, serverLookupObject }) => {
export const getSpecialRequest = ({ req, server, serverLookupObject }: IGetSpecialRequest) => {
// check data routes
let request;
let type;
if (server.dataRoutes) {
const dataSuffix = typeof server.dataRoutes === 'string' ? server.dataRoutes : 'data.json';
if (req.path.endsWith(dataSuffix)) {
const lookup = req.path.replace(dataSuffix, '');
request = serverLookupObject[lookup];
type = 'data';
}
}

if (server.allRequestsRoute) {
const dataSuffix = typeof server.allRequestsRoute === 'string' ? server.allRequestsRoute : '/allRequests.json';
if (req.path === dataSuffix) {
// just needs any request.
const k1 = Object.keys(serverLookupObject)[0];
request = serverLookupObject[k1];
type = 'allRequests';
}
}

if (request) {
request = JSON.parse(JSON.stringify(request));
request.req = req;
}

return request;
return { request, type };
};

interface IFindPrebuildRequest {
req: Req;
serverLookupObject: any;
}

export const findPrebuiltRequest = ({ req, serverLookupObject }: IFindPrebuildRequest): RequestOptions | false => {
// see if we have a request object with the path as is. (could include / or not.)
let request = serverLookupObject[req.path] ? serverLookupObject[req.path] : false;
Expand All @@ -72,6 +90,7 @@ export const findPrebuiltRequest = ({ req, serverLookupObject }: IFindPrebuildRe
}

if (request) {
request = JSON.parse(JSON.stringify(request));
request.req = req;
}

Expand Down Expand Up @@ -148,18 +167,24 @@ function prepareRouter(Elder) {
shortcodes: elder.shortcodes,
};

async function handleRequest({ res, next, request, dynamic = false, dataRequest = false }) {
async function handleRequest({ res, next, request, dynamic = false, type = '' }) {
if (!request.route || typeof request.route !== 'string') return next();
if (!routes[request.route]) return next();
const page = new Page({ ...forPage, request, next: dynamic ? next : undefined, route: routes[request.route] });
const { htmlString: html, data } = await page.build();
const { htmlString: html, data, allRequests } = await page.build();

if (dataRequest && data) {
if (type === 'data' && data) {
res.setHeader('Content-Type', 'application/json');
res.end(JSON.stringify(data));
return undefined;
}

if (type === 'allRequests' && allRequests) {
res.setHeader('Content-Type', 'application/json');
res.end(JSON.stringify(allRequests));
return undefined;
}

if (html && !res.headerSent && !res.headersSent) {
// note: html will be undefined if a dynamic route calls skip() as it aborts page building.
res.setHeader('Content-Type', 'text/html');
Expand All @@ -178,14 +203,17 @@ function prepareRouter(Elder) {
// initial request may be well formed if it is modified via a hook BEFORE the router runs.
if (initialRequestIsWellFormed(initialRequest)) return handleRequest({ res, next, request: initialRequest });
if (!needsElderRequest({ req, prefix })) return next();
const dataRequest = getDataRequest({ req, server: settings.server, serverLookupObject });
if (dataRequest) {
return handleRequest({ res, next, request: { ...dataRequest, ...initialRequest }, dataRequest: true });
const { request: specialRequest, type } = getSpecialRequest({
req,
server: settings.server,
serverLookupObject,
});
if (specialRequest) {
return handleRequest({ res, next, request: { ...specialRequest, ...initialRequest }, type });
}
const request = findPrebuiltRequest({
req,
serverLookupObject,
dataRoutes: settings && settings.server && settings.server.dataRoutes,
});
if (request) return handleRequest({ res, next, request: { ...request, ...initialRequest } });
const dynamicRequest = requestFromDynamicRoute({ req, dynamicRoutes, requestCache });
Expand Down
28 changes: 28 additions & 0 deletions src/utils/__tests__/__snapshots__/validations.spec.ts.snap
Original file line number Diff line number Diff line change
Expand Up @@ -789,6 +789,7 @@ Object {
"_exclusive": Object {},
"_mutate": undefined,
"_nodes": Array [
"allRequestsRoute",
"dataRoutes",
"cacheRequests",
"prefix",
Expand All @@ -804,6 +805,33 @@ Object {
"refs": Map {},
},
"fields": Object {
"allRequestsRoute": Object {
"_blacklist": Object {
"list": Set {},
"refs": Map {},
},
"_conditions": Array [],
"_default": false,
"_deps": Array [],
"_exclusive": Object {},
"_label": "Experimental: Allows for getting a json response of the all requests object by hitting a url. Defaults to /allRequests.json if \\"true\\" but can be overridden with any string.",
"_mutate": undefined,
"_options": Object {
"abortEarly": true,
"recursive": true,
},
"_type": "boolean",
"_typeError": [Function],
"_whitelist": Object {
"list": Set {},
"refs": Map {},
},
"tests": Array [],
"transforms": Array [
[Function],
],
"type": "boolean",
},
"cacheRequests": Object {
"_blacklist": Object {
"list": Set {},
Expand Down
1 change: 1 addition & 0 deletions src/utils/__tests__/validations.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,7 @@ describe('#validations', () => {
prefix: '',
cacheRequests: true,
dataRoutes: false,
allRequestsRoute: false,
},
shortcodes: {
closePattern: '}}',
Expand Down
4 changes: 3 additions & 1 deletion src/utils/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,11 @@ import type { HookOptions } from '../hooks/types';
import type { ShortcodeDefs } from '../shortcodes/types';
import Page from './Page';

type ServerOptions = {
export type ServerOptions = {
prefix: string;
cacheRequests?: boolean;
dataRoutes?: boolean | string;
allRequestsRoute?: boolean | string;
};

type BuildOptions = {
Expand Down
7 changes: 7 additions & 0 deletions src/utils/validations.ts
Original file line number Diff line number Diff line change
Expand Up @@ -112,6 +112,13 @@ const configSchema = yup.object({
.label(
'Experimental: Allows for getting a json response of the data object of a url. Defaults to [path]/data.json but can be any suffix/filename after the route.',
),
allRequestsRoute: yup
.boolean()
.notRequired()
.default(false)
.label(
'Experimental: Allows for getting a json response of the all requests object by hitting a url. Defaults to /allRequests.json if "true" but can be overridden with any string.',
),
}),
prefix: yup
.string()
Expand Down

0 comments on commit 0902435

Please sign in to comment.