From 188278e4951bed32cfcb76460bd52565f22317a0 Mon Sep 17 00:00:00 2001 From: Ashot Nazaryan Date: Wed, 29 May 2024 13:44:05 -0700 Subject: [PATCH] docs: Validation for custom methods (#3376) --- docs/api/schema/validators.md | 43 +++++++++++++++++++++++++++++++++++ docs/api/services.md | 2 +- 2 files changed, 44 insertions(+), 1 deletion(-) diff --git a/docs/api/schema/validators.md b/docs/api/schema/validators.md index 964ddf16ae..4ccc34a5c0 100644 --- a/docs/api/schema/validators.md +++ b/docs/api/schema/validators.md @@ -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): Promise> { + const { name } = data + return { response: `Hello ${name}` } +} +``` + +Finally, we can add our validator in our service hooks + +```ts +sayHello: [schemaHooks.validateData(sayHelloValidator)] +``` diff --git a/docs/api/services.md b/docs/api/services.md index c4ce843bfb..45a81c9ebf 100644 --- a/docs/api/services.md +++ b/docs/api/services.md @@ -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'