Skip to content

Commit

Permalink
fix: handle async functions in context
Browse files Browse the repository at this point in the history
  • Loading branch information
alexlafroscia committed Mar 21, 2021
1 parent 9a095e3 commit 8b5eef4
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 7 deletions.
24 changes: 20 additions & 4 deletions __tests__/context.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,19 +19,20 @@ test('it processes Handlebars variables', async () => {

test('it evaluates functions as `context` keys', async () => {
const temp = await factory.createStructure({
'index.html': '<p>{{foo}}</p>',
'index.html': '<p>{{foo}} {{bar}}</p>',
});
const result = await build(temp.dir, {
context: {
foo: () => 'bar',
foo: () => 'foo',
bar: () => Promise.resolve('bar'),
},
});
const html = getHtmlSource(result);

expect(html).toContain('<p>bar</p>');
expect(html).toContain('<p>foo bar</p>');
});

test('it evaluates a `context` function', async () => {
test('it evaluates a synchronous `context` function', async () => {
const temp = await factory.createStructure({
'index.html': '<p>{{foo}}</p>',
});
Expand All @@ -44,3 +45,18 @@ test('it evaluates a `context` function', async () => {

expect(html).toContain('<p>bar</p>');
});

test('it evaluates an asynchronous `context` function', async () => {
const temp = await factory.createStructure({
'index.html': '<p>{{foo}}</p>',
});
const result = await build(temp.dir, {
context: () =>
Promise.resolve({
foo: 'bar',
}),
});
const html = getHtmlSource(result);

expect(html).toContain('<p>bar</p>');
});
9 changes: 6 additions & 3 deletions src/context.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,7 @@
export type Context = Record<string, unknown> | (() => Record<string, unknown>);
export type Context =
| Record<string, unknown>
| (() => Record<string, unknown>)
| (() => Promise<Record<string, unknown>>);

export async function resolveContext(
context: Context | undefined
Expand All @@ -8,7 +11,7 @@ export async function resolveContext(
}

if (typeof context === 'function') {
return resolveContext(context());
return resolveContext(await context());
}

const output: Record<string, unknown> = {};
Expand All @@ -17,7 +20,7 @@ export async function resolveContext(
const value = context[key];

if (typeof value === 'function') {
output[key] = value();
output[key] = await value();
} else {
output[key] = context[key];
}
Expand Down

0 comments on commit 8b5eef4

Please sign in to comment.