Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Support async html transformer function #103

Merged
merged 1 commit into from
Jan 2, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
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
4 changes: 2 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -225,7 +225,7 @@ app.get('^nested/subroute/my/secret/path$', (_, res) => {

## 🤖 Transforming HTML

You can specify transformer function that takes two arguments - HTML as a string and [`Request`][express-request] object - and returns HTML as a string with any string related transformation applied. It can be used to inject your custom metadata on the server-side.
You can specify transformer function that takes two arguments - HTML as a string and [`Request`][express-request] object - and returns HTML as a string with any string related transformation applied. It can be used to inject your custom metadata on the server-side. It can also be an async function if you need to retrieve the data to inject from a database or some other remote source.

This transformer function is invoked right before sending the HTML to the client in the index-serving middleware that `vite-express` injects at the end of the middleware stack.

Expand Down Expand Up @@ -312,7 +312,7 @@ ViteExpress.config({ /*...*/ });
| name | description | default | valid values |
| ---------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------- | ----------------------------------------------------------------- |
| mode | When set to development Vite Dev Server will be utilized, in production app will serve static files built with `vite build` command | `"development"` | `"development"` \| `"production"` |
| transformer | A function used to transform HTML served to the client, useful when you want to inject some metadata on the server. First argument is the HTML that is about to be sent to the client, second is the [`Request`][express-request] object. Needs to return transformed HTML as a string. | `undefined` | `undefined` \| `(html: string, req: Request) => string` |
| transformer | A function used to transform HTML served to the client, useful when you want to inject some metadata on the server. First argument is the HTML that is about to be sent to the client, second is the [`Request`][express-request] object. Needs to return transformed HTML as a string, or a Promise that resolves to the transformed HTML string. | `undefined` | `undefined` \| `(html: string, req: Request) => string \| Promise<string>` |
| ignorePaths | A regex or function used to determine if matched path/request should be ignored by Vite index.html serving logic. When defined as a function, the request will be ignored when function returns true. Example of usage: Can be used to disable Vite on `/api` paths. | `undefined` | `undefined` \| `RegExp` \| `(path: string, req: Request) => bool` |
| inlineViteConfig | When set to non-undefined value, `vite-express` will be run in [`viteless mode`](#-viteless-mode) | `undefined` | `undefined` \| `ViteConfig` |

Expand Down
32 changes: 24 additions & 8 deletions src/main.ts
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ const Config = {
| ((path: string, req: express.Request) => boolean),
transformer: undefined as
| undefined
| ((html: string, req: express.Request) => string),
| ((html: string, req: express.Request) => string | Promise<string>),
};

type ConfigurationOptions = Partial<typeof Config>;
Expand All @@ -50,7 +50,7 @@ function isStaticFilePath(path: string) {
return path.match(/(\.\w+$)|@vite|@id|@react-refresh/);
}

function getTransformedHTML(html: string, req: express.Request) {
async function getTransformedHTML(html: string, req: express.Request) {
return Config.transformer ? Config.transformer(html, req) : html;
}

Expand Down Expand Up @@ -224,8 +224,16 @@ async function injectViteIndexMiddleware(
if (indexPath === undefined) return next();

const template = fs.readFileSync(indexPath, "utf8");
const html = await server.transformIndexHtml(req.originalUrl, template);
res.send(getTransformedHTML(html, req));
let html = await server.transformIndexHtml(req.originalUrl, template);

try {
html = await getTransformedHTML(html, req);
res.send(html);
} catch (e) {
console.error(e);
res.status(500);
return next();
}
}
});
}
Expand All @@ -234,14 +242,22 @@ async function injectIndexMiddleware(app: core.Express) {
const distPath = await getDistPath();
const config = await getViteConfig();

app.use(config.base, (req, res, next) => {
app.use(config.base, async (req, res, next) => {
if (isIgnoredPath(req.path, req)) return next();

const indexPath = findClosestIndexToRoot(req.path, distPath);
if (indexPath === undefined) return next();

const html = fs.readFileSync(indexPath, "utf8");
res.send(getTransformedHTML(html, req));
let html = fs.readFileSync(indexPath, "utf8");

try {
html = await getTransformedHTML(html, req);
res.send(html);
} catch (e) {
console.error(e);
res.status(500);
return next();
}
});
}

Expand All @@ -263,7 +279,7 @@ async function startServer(server: http.Server | https.Server) {
);

server.on("close", async () => {
await vite.close()
await vite.close();
server.emit("vite:close");
});

Expand Down