Skip to content

Commit

Permalink
docs: update nested service call examples
Browse files Browse the repository at this point in the history
  • Loading branch information
DawidWraga committed Apr 2, 2024
1 parent df1bbd3 commit da2add6
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 8 deletions.
20 changes: 13 additions & 7 deletions packages/service/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -34,20 +34,20 @@ export const mailAiGeneratedInvoice = authedService
.input(z.object({ to: z.string(), projectId: z.string() }))
.query(async ({ ctx, input }) => {
// each service is called directly, no API calls
await checkSufficientCredits({ amount: 10 });
await checkSufficientCredits(ctx, { amount: 10 });

// The inputs / outputs are type safe and validated by Zod
const pdf = await generatePdf({ html: project.invoiceHtml });
const pdf = await generatePdf(ctx, { html: project.invoiceHtml });

// Services are just functions - so no limitaitons of content types (eg files, streams, etc, can be passed around easily)
await sendEmail({
await sendEmail(ctx, {
to: input.to,
subject: 'Invoice',
body: 'Please find attached your invoice',
attachments: [{ filename: 'invoice.pdf', content: pdf }],
});

await deductCredits({ amount: 10 });
await deductCredits(ctx, { amount: 10 });

return 'Invoice sent';
});
Expand Down Expand Up @@ -126,6 +126,11 @@ export const authedService = service<AuthedServiceCtx>().use(
return next(ctx);
}
);

export function createServiceCtx() {
const user = auth();
return { user, db };
}
```

### Defining a Service
Expand Down Expand Up @@ -167,7 +172,8 @@ const getTasks = service()
Unlike tRPC procedures, services can be called directly from anywhere in your backend, including within other services.

```typescript
const tasks = await getTasks({ projectId: '...' });
const ctx = createServiceCtx();
const tasks = await getTasks(ctx, { projectId: '...' });
```

This allows you to build complex service logic by composing multiple services together.
Expand All @@ -183,8 +189,8 @@ const getProjectDetails = service()
})
)
.query(async ({ ctx, input }) => {
const project = await getProject(input.projectId);
const tasks = await getTasks({ projectId: input.projectId });
const project = await getProject(ctx, { projectId: input.projectId });
const tasks = await getTasks(ctx, { projectId: input.projectId });
return { ...project, tasks };
});
```
Expand Down
2 changes: 1 addition & 1 deletion packages/service/package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "@davstack/service",
"version": "0.1.9",
"version": "0.2.0",
"main": "./dist/index.js",
"module": "./dist/index.mjs",
"types": "./dist/index.d.ts",
Expand Down

0 comments on commit da2add6

Please sign in to comment.