Skip to content
This repository was archived by the owner on Feb 23, 2025. It is now read-only.

refactor: simplify server entrypoint #373

Closed
wants to merge 30 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
30 commits
Select commit Hold shift + click to select a range
3293513
refactor: add entry-hattip
hi-ogawa May 6, 2023
2dd9e02
wip
hi-ogawa May 6, 2023
81845e5
Merge branch 'master' into refactor-server-entrypoint
hi-ogawa May 26, 2023
8ae519c
chore: add hattip entry
hi-ogawa May 26, 2023
3f8cf80
chore: add dev-server.sh
hi-ogawa May 26, 2023
2b739d6
fix: remove installGlobals + node 18
hi-ogawa May 26, 2023
35ddf31
chore: add wait-for.sh
hi-ogawa May 26, 2023
11ef49e
chore: tweak script
hi-ogawa May 26, 2023
4fb0fcd
chore: tweak e2e
hi-ogawa May 26, 2023
7d01ba9
chore: remove unused
hi-ogawa May 26, 2023
7ef2bce
ci: node 18
hi-ogawa May 26, 2023
4ce2322
Merge branch 'master' into refactor-server-entrypoint
hi-ogawa May 26, 2023
97d12fc
chore: simplify initialization
hi-ogawa May 26, 2023
f3fa16c
chore: lint
hi-ogawa May 26, 2023
0145c08
test: fix e2e coverage
hi-ogawa May 26, 2023
83fa69d
chore: move noSourceMapNodeModulesPlugin to remix config
hi-ogawa May 26, 2023
ec66caf
chore: remove unused
hi-ogawa May 26, 2023
27e6565
chore: give up sourcemap
hi-ogawa May 26, 2023
4e7efdb
refactor: simplify public assets
hi-ogawa May 26, 2023
e5e0684
Merge branch 'master' into refactor-server-entrypoint
hi-ogawa May 28, 2023
2c847b7
fix: fix dev server reload
hi-ogawa May 28, 2023
9490af7
chore: tweak serverDependenciesToBundle
hi-ogawa May 28, 2023
9717c8c
chore: tweak cache
hi-ogawa May 28, 2023
903503f
chore: comment
hi-ogawa May 28, 2023
eab1d2f
chore: lint
hi-ogawa May 28, 2023
e06b601
chore: lint
hi-ogawa May 28, 2023
038ab01
chore: fix dev-server.sh
hi-ogawa May 28, 2023
71d1e0b
chore: revert globalThis hack
hi-ogawa May 28, 2023
7b986e7
chore: remove unused
hi-ogawa May 28, 2023
f0ba97f
chore: tweak LiveReload
hi-ogawa May 28, 2023
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 9 additions & 9 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -8,10 +8,10 @@ jobs:
- uses: actions/checkout@v3
- uses: pnpm/action-setup@v2
with:
version: 7
version: 8
- uses: actions/setup-node@v3
with:
node-version: 16
node-version: 18
cache: pnpm
- run: make lint
- run: pnpm i
Expand All @@ -25,10 +25,10 @@ jobs:
- uses: actions/checkout@v3
- uses: pnpm/action-setup@v2
with:
version: 7
version: 8
- uses: actions/setup-node@v3
with:
node-version: 16
node-version: 18
cache: pnpm
- run: pnpm i
- run: make docker/up db/reset/test db/seed-download
Expand All @@ -44,10 +44,10 @@ jobs:
- uses: actions/checkout@v3
- uses: pnpm/action-setup@v2
with:
version: 7
version: 8
- uses: actions/setup-node@v3
with:
node-version: 16
node-version: 18
cache: pnpm
- run: pnpm i
- uses: actions/cache@v3
Expand Down Expand Up @@ -76,10 +76,10 @@ jobs:
- uses: actions/checkout@v3
- uses: pnpm/action-setup@v2
with:
version: 7
version: 8
- uses: actions/setup-node@v3
with:
node-version: 16
node-version: 18
cache: pnpm
- run: pnpm i
- run: make docker/up db/recreate
Expand All @@ -103,7 +103,7 @@ jobs:
- uses: actions/checkout@v3
- uses: actions/setup-node@v3
with:
node-version: 16
node-version: 18
- uses: actions/download-artifact@v3
with:
name: coverage-unit
Expand Down
1 change: 0 additions & 1 deletion app/assets/.gitignore

This file was deleted.

11 changes: 0 additions & 11 deletions app/assets/README.md

This file was deleted.

1 change: 0 additions & 1 deletion app/e2e/videos.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -224,7 +224,6 @@ test.describe("video playback rate", () => {
await page
.getByTestId("PlaybackRateSelect")
.selectOption({ label: "0.75" });
await page.pause();
});
});

Expand Down
3 changes: 0 additions & 3 deletions app/entry.server.tsx
Original file line number Diff line number Diff line change
@@ -1,9 +1,6 @@
import { RemixServer } from "@remix-run/react";
import type { HandleDocumentRequestFunction } from "@remix-run/server-runtime";
import { renderToString } from "react-dom/server";
import { injectInitializeServer } from "./misc/initialize-server";

injectInitializeServer();

const handler: HandleDocumentRequestFunction = (
request,
Expand Down
12 changes: 2 additions & 10 deletions app/misc/initialize-server.ts
Original file line number Diff line number Diff line change
@@ -1,24 +1,16 @@
import { once } from "@hiogawa/utils";
import { installGlobals } from "@remix-run/node";
import {
finalizeDrizzleClient,
initializeDrizzleClient,
} from "../db/drizzle-client.server";
import { initializeConfigServer } from "../utils/config";
import { initializeSessionStore } from "../utils/session.server";

export const initializeServer = once(async () => {
installGlobals();
export async function initializeServer() {
initializeConfigServer();
initializeSessionStore();
await initializeDrizzleClient();
});
}

export async function finalizeServer() {
await finalizeDrizzleClient();
}

// to workaround async initialization on the server (cf. @remix-run/server-runtime patch)
export function injectInitializeServer() {
Object.assign(globalThis, { __onRequestHandler: initializeServer });
}
4 changes: 2 additions & 2 deletions app/root.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@ export const links: LinksFunction = () => {
// prettier-ignore
return [
{ rel: "stylesheet", href: require("../build/css/index.css") },
{ rel: "icon", href: require("./assets/icon-32.png"), sizes: "32x32" },
{ rel: "icon", href: "/favicon.ico" },
{ rel: "manifest", href: "/manifest.json" },
];
};
Expand Down Expand Up @@ -132,7 +132,7 @@ function Root() {
</div>
</div>
<Scripts />
<LiveReload />
{process.env.NODE_ENV !== "production" && <LiveReload />}
</>
);
}
Expand Down
41 changes: 0 additions & 41 deletions app/routes/manifest[.json].tsx

This file was deleted.

17 changes: 0 additions & 17 deletions app/routes/service-worker[.js].tsx

This file was deleted.

22 changes: 0 additions & 22 deletions app/routes/trpc/$trpc.tsx

This file was deleted.

58 changes: 58 additions & 0 deletions app/server/entry-dev.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
import fs from "node:fs";
import { createServer } from "node:http";
import path from "node:path";
import process from "node:process";
import { createMiddleware } from "@hattip/adapter-node";
import express from "express";
import { listenPortSearchByEnv } from "./http";

async function main() {
//
// require buildPath with require.cache invalidation
//

const buildPath = path.resolve(process.argv[2]);

// require.cache trick as a cheap live reload
function requireBuild() {
console.log(`[entry-dev] Loading ${buildPath}`);
delete require.cache[buildPath];
return require(path.resolve(buildPath)) as typeof import("./entry-hattip");
}

let build = requireBuild();
fs.watch(path.dirname(buildPath), (eventType, filename) => {
if (eventType === "change" && path.basename(buildPath) === filename) {
build = undefined!;
}
});

//
// express app
//

const app = express();
const server = createServer(app);

// serve client build assets
app.use(
"/build",
express.static(build.assetsBuildDirectory, {
immutable: true,
maxAge: "1y",
})
);
app.use("/", express.static("./public"));

// main logic as hattip handler
app.all("*", (req, res, next) => {
build ??= requireBuild();
return createMiddleware(build.createHattipApp())(req, res, next);
});

// start app
const port = await listenPortSearchByEnv(server);
console.log(`[entry-dev] Server running at http://localhost:${port}`);
}

main();
97 changes: 97 additions & 0 deletions app/server/entry-hattip.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,97 @@
import { type RequestHandler, compose } from "@hattip/compose";
import { once } from "@hiogawa/utils";
import * as build from "@remix-run/dev/server-build";
import { createRequestHandler } from "@remix-run/server-runtime";
import { fetchRequestHandler } from "@trpc/server/adapters/fetch";
import type * as hono from "hono";
import { logger } from "hono/logger";
import { initializeServer } from "../misc/initialize-server";
import { TRPC_ENDPOINT } from "../trpc/common";
import { createTrpcAppContext } from "../trpc/context";
import { trpcApp } from "../trpc/server";

// based on https://github.com/hi-ogawa/vite-fullstack-example/blob/92649f99b041820ec86650c99cfcd49a72e79f71/src/server/hattip.ts#L16-L28

export function createHattipApp() {
return compose(
createLogger(),
createBootstrapHandler(),
createTrpchandler(),
createRemixHandler()
);
}

// re-export for entry-dev
// ts-prune-ignore-next
export const assetsBuildDirectory = build.assetsBuildDirectory;

//
// remix
//

function createRemixHandler(): RequestHandler {
const remixHandler = createRequestHandler(build);
return async (ctx) => {
const response = await remixHandler(ctx.request);
return response;
};
}

//
// trpc
//

function createTrpchandler(): RequestHandler {
return async (ctx) => {
if (!ctx.url.pathname.startsWith(TRPC_ENDPOINT)) {
return ctx.next();
}
return fetchRequestHandler({
endpoint: TRPC_ENDPOINT,
req: ctx.request,
router: trpcApp,
createContext: createTrpcAppContext,
onError: (e) => {
console.error(e);
},
});
};
}

//
// bootstrap
//

function createBootstrapHandler(): RequestHandler {
const initializeServerOnce = once(initializeServer);
return async (ctx) => {
await initializeServerOnce();
return ctx.next();
};
}

//
// logger
//

function createLogger(): RequestHandler {
// borrow hono's logger by minimal hattip-hono compatibility layer
// https://github.com/honojs/hono/blob/0ffd795ec6cfb67d38ab902197bb5461a4740b8f/src/middleware/logger/index.ts
const honoLogger = logger();

return async (ctx) => {
let res!: Response;
await honoLogger(
{
req: { method: ctx.method, raw: ctx.request },
get res() {
return res;
},
} as hono.Context,
async () => {
res = await ctx.next();
}
);
return res;
};
}
12 changes: 12 additions & 0 deletions app/server/entry-vercel.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
import { createMiddleware } from "@hattip/adapter-node";
import { createHattipApp } from "./entry-hattip";

// cf. https://github.com/hattipjs/hattip/blob/03a704fa120dfe2eddd6cf22eff00c90bda2acb5/packages/bundler/bundler-vercel/readme.md

export default createVercelHanlder();

function createVercelHanlder() {
return createMiddleware(createHattipApp(), {
trustProxy: true,
});
}
Loading