|
1 | 1 | # OPA Typescript SDK |
2 | 2 |
|
| 3 | +Styra's OPA SDK |
| 4 | + |
3 | 5 | [](https://opensource.org/licenses/Apache-2.0) |
4 | 6 |
|
5 | 7 | <!-- Start SDK Installation [installation] --> |
@@ -190,6 +192,59 @@ const allowed = await opa.authorize<any, boolean>( |
190 | 192 | console.log(allowed ? "allowed!" : "denied!"); |
191 | 193 | ``` |
192 | 194 |
|
| 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 | + |
193 | 248 | > [!NOTE] |
194 | 249 | > For low-level SDK usage, see the sections below. |
195 | 250 |
|
|
0 commit comments