Skip to content
This repository was archived by the owner on Jul 1, 2024. It is now read-only.

Commit 4ba4ea7

Browse files
authored
README: add examples, links and snippets (#42)
Signed-off-by: Stephan Renatus <stephan@styra.com>
1 parent 07004ec commit 4ba4ea7

File tree

1 file changed

+55
-0
lines changed

1 file changed

+55
-0
lines changed

README.md

Lines changed: 55 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,7 @@
11
# OPA Typescript SDK
22

3+
Styra's OPA SDK
4+
35
[![License](https://img.shields.io/badge/License-Apache_2.0-blue.svg)](https://opensource.org/licenses/Apache-2.0)
46

57
<!-- Start SDK Installation [installation] -->
@@ -190,6 +192,59 @@ const allowed = await opa.authorize<any, boolean>(
190192
console.log(allowed ? "allowed!" : "denied!");
191193
```
192194

195+
### Example Projects
196+
197+
#### Express
198+
199+
In [the StyraInc/styra-demo-tickethub repository](https://github.com/StyraInc/styra-demo-tickethub/tree/main/server/node), you'll find a NodeJS backend service that is using `@styra/opa`:
200+
201+
```javascript
202+
router.get("/tickets/:id", [param("id").isInt().toInt()], async (req, res) => {
203+
const {
204+
params: { id },
205+
} = req;
206+
await authz.authorized(path, { action: "get", id }, req);
207+
208+
const ticket = await prisma.tickets.findUniqueOrThrow({
209+
where: { id },
210+
...includeCustomers,
211+
});
212+
return res.status(OK).json(toTicket(ticket));
213+
});
214+
```
215+
216+
#### NestJS
217+
218+
In [StyraInc/opa-typescript-example-nestjs](https://github.com/StyraInc/opa-typescript-example-nestjs), we have an decorator-based API authorization example using `@styra/opa`:
219+
220+
```ts
221+
@Controller('cats')
222+
@AuthzQuery('cats/allow')
223+
@AuthzStatic({ resource: 'cat' })
224+
export class CatsController {
225+
constructor(private catsService: CatsService) {}
226+
227+
@Post()
228+
@Authz(({ body: { name } }) => ({ name, action: 'create' }))
229+
async create(@Body() createCatDto: CreateCatDto) {
230+
this.catsService.create(createCatDto);
231+
}
232+
233+
@Get(':name')
234+
@AuthzQuery('cats') // For illustration, we're querying the package extent
235+
@Decision((r) => r.allow)
236+
@Authz(({ params: { name } }) => ({
237+
name,
238+
action: 'get',
239+
}))
240+
async findByName(@Param('name') name: string): Promise<Cat> {
241+
return this.catsService.findByName(name);
242+
}
243+
}
244+
```
245+
246+
Please refer to [the repository's README.md](https://github.com/StyraInc/opa-typescript-example-nestjs/tree/main#opa-typescript-nestjs-example) for more details.
247+
193248
> [!NOTE]
194249
> For low-level SDK usage, see the sections below.
195250

0 commit comments

Comments
 (0)