Skip to content

Commit

Permalink
docs: Validation for custom methods (#3376)
Browse files Browse the repository at this point in the history
  • Loading branch information
AshotN authored May 29, 2024
1 parent d654808 commit 188278e
Show file tree
Hide file tree
Showing 2 changed files with 44 additions and 1 deletion.
43 changes: 43 additions & 0 deletions docs/api/schema/validators.md
Original file line number Diff line number Diff line change
Expand Up @@ -115,3 +115,46 @@ app.service('messages').hooks({
}
})
```

### Using validators with custom methods

You can optionally create validators for your custom methods. For example we will create a custom method in our `user` service that simply says "Hello ${name}" to the requestor.

For the example we can use this TypeBox schema

```ts
//Our request object, we expect something like {name: "Bob"}
export const sayHelloRequest = Type.Object(
{
name: Type.String({
description: "Who are we saying hello to!",
examples: ["Bob"],
minLength: 2,
}),
},
{ $id: "sayHelloRequest", additionalProperties: false },
);

//We intend on returning an object with a string response property
export const sayHelloResponse = Type.Object(
{ response: Type.String() },
{ $id: "sayHelloResponse", additionalProperties: false },
);

export const sayHelloValidator = getValidator(sayHelloRequest, dataValidator);
```

In our user class file, we can define our custom method

```ts
async sayHello(data: Static<typeof sayHelloRequest>): Promise<Static<typeof sayHelloResponse>> {
const { name } = data
return { response: `Hello ${name}` }
}
```

Finally, we can add our validator in our service hooks

```ts
sayHello: [schemaHooks.validateData(sayHelloValidator)]
```
2 changes: 1 addition & 1 deletion docs/api/services.md
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ Services are the heart of every Feathers application. Services are objects or in

## Service methods

Service methods are pre-defined [CRUD](https://en.wikipedia.org/wiki/Create,_read,_update_and_delete) and [custom methods](#custommethod-data-params) that your service provides or that have already been implemented by one of the [database adapters](./databases/common.md). Below is an example of a Feathers service as a class or object.
Service methods are pre-defined [CRUD](https://en.wikipedia.org/wiki/Create,_read,_update_and_delete) and [custom methods](#custom-methods) that your service provides or that have already been implemented by one of the [database adapters](./databases/common.md). Below is an example of a Feathers service as a class or object.

```ts
import { feathers } from '@feathersjs/feathers'
Expand Down

0 comments on commit 188278e

Please sign in to comment.