You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
feat: add response validation to the client (#373)
* feat: automatic validating the schema on the client
* feat: add a flag to enable/disable the client validation behaviour
* chore: add minor changeset to the ts-rest/core package
* Update afraid-eagles-report.md
* docs: add guidelines for the `validateResponseOnClient` option
* docs: add notes for those using zod as the schema validator
* docs: move the caution for schema validation to the correct spot
---------
Co-authored-by: Michael Angelo Rivera <55844504+michaelangeloio@users.noreply.github.com>
By default, all responses are inferred at the type-level by the client using the contract, and are not validated at runtime.
174
+
175
+
However, you can use the `validateResponseOnClient` option to validate the response at runtime by checking it against the defined schema associated with the status code in the contract. By default, this option is set to `false`.
176
+
177
+
If you would like to enable this functionality for all routes in the contract, you can set the `validateResponseOnClient` option to `true` when initializing the contract.
178
+
179
+
```typescript
180
+
const c =initContract();
181
+
exportconst contract =c.router({
182
+
{
183
+
// ...endpoints
184
+
},
185
+
{
186
+
validateResponseOnClient: true,
187
+
}
188
+
});
189
+
```
190
+
191
+
You can also control this option on a per-route basis which will also override the globally set option.
192
+
193
+
```typescript
194
+
const c =initContract();
195
+
exportconst contract =c.router({
196
+
getPosts: {
197
+
...,
198
+
validateResponseOnClient: true,
199
+
}
200
+
});
201
+
```
202
+
203
+
:::caution
204
+
When using `zod` as the schema, should the validation fail, the error will be thrown as a `ZodError`.
205
+
206
+
You can catch this error and handle it however you like.
207
+
208
+
```typescript
209
+
try {
210
+
const posts =awaitclient.getPosts();
211
+
} catch (error) {
212
+
if (errorinstanceofZodError) {
213
+
// handle error
214
+
}
215
+
}
216
+
```
217
+
218
+
:::
219
+
168
220
## Combining Contracts
169
221
170
222
You can combine contracts to create a single contract, helpful if you want many sub-contracts, especially if they are huge.
@@ -254,13 +306,16 @@ You can assign `baseHeaders` which will be merged with the contract `headers`. H
0 commit comments