Skip to content

Commit

Permalink
refactor to build pages->headers map during onPostBuild
Browse files Browse the repository at this point in the history
- refactor `header-builder.ts` to loop through all possible pages/files and add their matching headers during `onPostBuild`
- refactor `headers.ts` fastify plugin to look up headers for the path and add them, alongside default security, respecting overwrite precedence
- add `reply.mode` and `reply.path` decorators to support adding headers to dynamic routes via the matched path rather than `request.url`
- add tests to support feature table in #392, specifically: #392 (comment)
  • Loading branch information
tsdexter committed Mar 17, 2023
1 parent abd1fe5 commit 897e7d5
Show file tree
Hide file tree
Showing 34 changed files with 755 additions and 136 deletions.
12 changes: 11 additions & 1 deletion integration-tests/plugin-fastify/gatsby-config.js
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ module.exports = {
headers: {
customHeaders: {
"/posts/page-1*": {
"x-test-page-specific": "shows on /posts/page-1 and its page-data",
"x-test-page-specific": "shows on /posts/page-1",
},
"/posts/page-2*": {
"X-Content-Type-Options": "nosniff by default, overwritten for this page",
Expand All @@ -50,6 +50,16 @@ module.exports = {
"x-test-ssr-kept": "ssr page",
"x-test-ssr-overwrite": "ssr page",
},
"/api/test": {
"x-test-function-kept": "function page",
"x-test-function-overwrite": "function page",
},
"/generated/page-6": {
"x-test-dsg-kept": "dsg page",
},
"/page-data/generated/page-6/page-data.json": {
"x-test-dsg-kept": "dsg page data",
},
"/posts/page-1/index.html": {
"x-test-page-specific": "shows on /posts/page-1 and its page-data (overwritten)",
},
Expand Down
4 changes: 4 additions & 0 deletions integration-tests/plugin-fastify/src/api/test.js
Original file line number Diff line number Diff line change
Expand Up @@ -271,8 +271,12 @@ const responseData = [

export default function handler(req, res) {
if (isGatsbyHosting(res)) {
res.setHeader("x-test-function-overwrite", "Overwritten by FUNCTION");
res.status(200).send(responseData);
} else {
res.headers({
"x-test-function-overwrite": "Overwritten by FUNCTION",
});
res.code(200).send(responseData);
}
}
3 changes: 3 additions & 0 deletions integration-tests/plugin-fastify/src/pages/index.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import * as React from "react";
import { Link, withPrefix } from "gatsby";
import { StaticImage } from "gatsby-plugin-image";

import "../../src/styles/test.css";

Expand Down Expand Up @@ -156,6 +157,8 @@ const IndexPage = () => {
<a href={withPrefix("/ssr_named_splat/test/path")}>Named Splat routed SSR page</a>
</li>
</ul>

<StaticImage src="../images/icon.png" alt="Icon" layout="fixed" width={165} />
</main>
);
};
Expand Down
Binary file added integration-tests/plugin-fastify/static/test.pdf
Binary file not shown.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
console.log("Hello from app-hash.js");
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
console.log("Hellow from component-fake-hash.js");
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
body { border: 1px solid red; }
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
console.log("Hello from fake-chunk.js");
Original file line number Diff line number Diff line change
@@ -1 +1 @@
console.log("this is a fake lazy component");
console.log("Hello from fake-lazycomponent.js");
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
{"webpackCompilationHash":"cf2f9feb0b0d2002462c"}
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
{"componentChunkName":"component---src-pages-posts-page-1-js","path":"/posts/page-1/","result":{"pageContext":{}},"staticQueryHashes":[],"slicesMap":{}}
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
{"componentChunkName":"component---src-pages-posts-page-2-js","path":"/posts/page-2/","result":{"pageContext":{}},"staticQueryHashes":[],"slicesMap":{}}
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
{"componentChunkName":"component---src-pages-posts-page-3-js","path":"/posts/page-3/","result":{"pageContext":{}},"staticQueryHashes":[],"slicesMap":{}}
Binary file not shown.
22 changes: 22 additions & 0 deletions packages/gatsby-plugin-fastify/src/__tests__/__utils__/config.js
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,28 @@ export function createCliConfig({ host, port, logLevel, open }) {
export async function createFastifyInstance(plugin) {
const config = getConfig();

config.server.headers = {
...config.server.headers,
"/component-fake-hash.js": {
"cache-control": "public, max-age=31536000, immutable",
"x-test-js": "root js file",
"x-cache-control": "overwrite cache-control for all root js files",
"x-test-all-pages": "shows on every page/file",
},
"/_gatsby/image/hash/hash/indonesia.jpg": {
"cache-control": "undefined",
"x-test-all-pages": "shows on every page/file",
},
"/static/hash/hash/icon.png": {
"cache-control": "public, max-age=31536000, immutable",
"x-test-all-pages": "shows on every page/file",
},
"/fake-lazycomponent.js": {
"cache-control": "undefined",
"x-test-all-pages": "shows on every page/file",
},
};

const fastify = Fastify(createFastifyConfig(config));

await fastify.register(plugin, { prefix: config.server.prefix });
Expand Down
66 changes: 46 additions & 20 deletions packages/gatsby-plugin-fastify/src/__tests__/gatsby-node.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,13 @@ import fs from "fs-extra";
import mockPath from "node:path";
import { onPostBuild } from "../gatsby-node";

function mockPosixJoin(...paths) {
return mockPath
.join(...paths)
.split(mockPath.sep)
.join(mockPath.posix.sep);
}

jest.mock("../utils/constants", () => ({
...jest.requireActual("../utils/constants"),
PATH_TO_FUNCTIONS: "../../integration-tests/plugin-fastify/.cache/functions/",
Expand All @@ -12,7 +19,7 @@ jest.mock("../utils/constants", () => ({

jest.mock("fs-extra", () => ({
existsSync: jest.fn((filePath) => {
if (filePath.includes(mockPath.join(".cache", "functions"))) {
if (filePath.includes(mockPosixJoin(".cache", "functions"))) {
return true;
}
return false;
Expand Down Expand Up @@ -51,30 +58,31 @@ jest.mock("fs-extra", () => ({
}),
}));

const mockPages = [
{
fakePage: "fakeValue",
path: "/",
},
{
matchPath: "/app/*",
path: "/app/[...]/",
},
{
path: "/ssr",
mode: "SSR",
},
{
path: "/my/dsg/path",
mode: "DSG",
},
];
const pathPrefix = "/test";
const store = {
getState: jest.fn(() => ({
program: {
directory: "",
},
pages: [
{
fakePage: "fakeValue",
path: "/",
},
{
matchPath: "/app/*",
path: "/app/[...]/",
},
{
path: "/ssr",
mode: "SSR",
},
{
path: "/my/dsg/path",
mode: "DSG",
},
],
pages: mockPages,
redirects: [
{
fromPath: "/perm-redirect",
Expand Down Expand Up @@ -102,6 +110,24 @@ const store = {
})),
};

jest.mock("../utils/plugin-data", () => ({
...jest.requireActual("../utils/plugin-data"),
makePluginData: jest.fn(() => ({
pages: new Map(Object.entries(mockPages).map(([key, value]) => [key, value])),
components: [],
manifest: [],
program: {},
pathPrefix: "",
publicFolder: jest.fn(() => "/public"),
functionsFolder: jest.fn((file) =>
file ? mockPosixJoin(".cache", "functions", file) : mockPosixJoin(".cache", "functions")
),
configFolder: jest.fn((file) =>
file ? mockPosixJoin(".cache", file) : mockPosixJoin(".cache")
),
})),
}));

const reporter = {
error: jest.fn((_message, error) => {
throw new Error(error);
Expand All @@ -125,7 +151,7 @@ describe(`Gatsby Node API`, () => {

const writeJSONCall = fs.writeJSON.mock.calls[0];
expect(fs.writeJSON).toHaveBeenCalledTimes(1);
expect(writeJSONCall[0]).toContain(mockPath.join(".cache", "gatsby-plugin-fastify.json"));
expect(writeJSONCall[0]).toContain(mockPosixJoin(".cache", "gatsby-plugin-fastify.json"));
expect(writeJSONCall[1]).toMatchSnapshot();
});
});
Loading

0 comments on commit 897e7d5

Please sign in to comment.