Skip to content

Commit

Permalink
feat: hoth-view support render with cb function
Browse files Browse the repository at this point in the history
  • Loading branch information
zhangqichao02 authored and meixg committed Jul 12, 2022
1 parent 537ad7f commit dae51e8
Show file tree
Hide file tree
Showing 2 changed files with 51 additions and 2 deletions.
41 changes: 41 additions & 0 deletions packages/view/__tests__/swig.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -131,4 +131,45 @@ describe('reply.render with swig engine', () => {
expect(response.body).toBe('<h1>fastify</h1>\n<p>text</p>');
expect(response.headers['content-type']).toBe('text/html; charset=utf-8');
});

it('render with cb', async () => {
const fastifyInstance = fastify();
const data = {
title: 'fastify',
text: 'text'
};

fastifyInstance.register(view, {
engine: {
swig: Swig,
},
templatesDir: __dirname
});

fastifyInstance.get('/', async (req: FastifyRequest, reply: FastifyReply) => {
const renderPage = () => {
return new Promise(function (resolve, reject) {
reply.render('templates/index.swig', data, function (err, html) {
if (err) {
reject(err);
return;
}
resolve(html + '<p>cbRender</p>');
});
});
};
const html = await renderPage();
expect(html).toBe('<h1>fastify</h1>\n<p>text</p><p>cbRender</p>');
reply.header('content-type', 'text/html; charset=utf-8');
reply.send(html);
});

const response = await fastifyInstance.inject({
method: 'GET',
path: '/'
});
expect(response.statusCode).toBe(200);
expect(response.body).toBe('<h1>fastify</h1>\n<p>text</p><p>cbRender</p>');
expect(response.headers['content-type']).toBe('text/html; charset=utf-8');
});
});
12 changes: 10 additions & 2 deletions packages/view/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,7 @@ export interface HothViewOptions {

declare module 'fastify' {
interface FastifyReply {
render(page: string, data?: Record<string, unknown>): FastifyReply;
render(page: string, data?: Record<string, unknown>, cb?: (err: Error, html: string) => void): FastifyReply;
// locals?: object;
}
}
Expand Down Expand Up @@ -127,7 +127,15 @@ async function plugin(fastify: FastifyInstance, opts: HothViewOptions) {

const renderer = renders[type];

fastify.decorateReply('render', function (this: FastifyReply, page: string, data: Record<string, unknown>) {
fastify.decorateReply('render', function (
this: FastifyReply,
page: string,
data: Record<string, unknown>,
cb?: (err: Error, html: string) => void
) {
if (cb && typeof cb === 'function') {
return renderer.apply(this, [page, data, cb]);
}
return new Promise((resolve, reject) => {
const done = (error: Error, html: string) => {
if (error) {
Expand Down

0 comments on commit dae51e8

Please sign in to comment.