Skip to content

Commit

Permalink
Support async html transformer function
Browse files Browse the repository at this point in the history
Having an async function to transform the html allows for more complex transformations, such as inserting data fetched from a database
  • Loading branch information
peterlama committed Dec 29, 2023
1 parent 1189de8 commit 9c5a0c4
Showing 1 changed file with 11 additions and 4 deletions.
15 changes: 11 additions & 4 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,15 @@ 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 Down

0 comments on commit 9c5a0c4

Please sign in to comment.