moleculer-zod-validator v3.3.1
moleculer-zod-validator
Validate Moleculer action parameters using the Zod validator.
Supports
Requires
As of v3.0.0, this package requires Node.js v17.0.0 or above.
Install
npm install moleculer-zod-validator
Usage
Broker
Import ZodValidator, then set up the validator in your broker settings using the validator property. For example:
// JavaScript
const { ServiceBroker } = require("moleculer");
const { ZodValidator } = require("moleculer-zod-validator");
// TypeScript
import { ServiceBroker } from "moleculer";
import { ZodValidator } from "moleculer-zod-validator";
const broker = new ServiceBroker({
validator: new ZodValidator()
});As of v3.0.0, moleculer-zod-validator implements the default Moleculer validator (fastest-validator) as a compatibility fallback for fastest-validator schemas, like those used in Moleculer's internal services, so calling services using that should not be a problem.
Actions
One of Zod's main features is how it can infer TypeScript types from a schema. To simplify the usage of this, there is a convenience utility called ZodParams that allows for easy access to the necessary data.
The ZodParams constructor takes one to three arguments: schema, optionally options, and optionally returnValue.
schema- This is a schema object that gets passed directly intoz.object. For all available schema options, please look at the Zod documentation.options- This provides access to some of the different functions available on a standard Zod object. All booleans default tofalseexcept forstrip, which is implicitly set totrue.partial(boolean) - Shallowly makes all properties optional. (docs)deepPartial(boolean) - Deeply makes all properties optional. (docs)strip(boolean) - Removes unrecognized keys from the parsed input. This is Zod's default behavior and this validator's default behavior. Mutually exclusive withpassthroughandstrict, and will override them if set. (docs)passthrough(boolean) - Passes through unrecognized keys. Mutually exclusive withstrictandstrip. (docs)strict(boolean) - Throws an error if unrecognized keys are present. Mutually exclusive withpassthroughandstrip. (docs)catchall(Zod validator) - Validates all unknown keys against this schema. Obviatesstrict,passthrough, andstrip. (docs)NOTE: There is currently an upstream bug in Zod that prevents
catchalltype inference from working correctly. Type inference for catchall in ZodParams is disabled for the time being until that is fixed. If you wish to emulate the type inference, you can do so by using a type union when usingbroker.callorctx.call.broker.call< ReturnType, typeof zodParamObject.call & {[index: string]: string} >({ ... })refine(function OR object) - Adds custom validation logic to the Zod object that can't be represented in TypeScript's type system or purely using Zod validators on their own (for example, making sure that at least one of several optional items are present). Returning any falsy value will fail validation, while returning any truthy value will pass validation. (docs)There are two ways to use this property. You can either pass in a validation function taking one parameter (representing the object being passed in) or an object with optionally two properties.
validator(function) - A validation function taking one parameter, representing the object being validated currently.params(object, optional) - Additional properties to customize the error handling behavior, as described in the Zod documentation
If both
refineandsuperRefineare defined,refinewill run last (aftersuperRefine).superRefine(function) - Adds custom validation logic to the Zod object that can't be represented in TypeScript's type system or purely using Zod validators on their own (for example, making sure that at least one of several optional items are present). This is a more powerful and verbose method of performing refinements. Validation will pass unlessctx.addIssueis called. (docs)This property takes a function with two arguments,
valandctx(not to be confused with Moleculer'sctxoption).val(object) - An object representing the object being validated currently.ctx(object) - An object provided by Zod.
If both
refineandsuperRefineare defined,superRefinewill run first (beforerefine).
returnType- The return type of the action in question. It does not matter what actual value is passed in, so long as it is given the desired return types using theaskeyword. Once stored, these can be referred to in the same way that you would access.calland.context. This can be done like so:new ZodParams({ property: z.string() }, undefined, {} as Promise<string>); ... const returnedValue = broker.call<typeof sampleParam.return, typeof sampleParam.call>({ property: "whatever" }); // type of returnedValue is Promise<string>
Additionally, support for object transformations is present, allowing for the use of features such as preprocessing, refinements, transforms, and defaults.
Once constructed, there are five properties exposed on the ZodParams object.
schema- The raw schema passed in. This should be passed to theparamsobject in the action definition.context- The inferred output type from the compiled validator. This should be used within theContextobject in the action definition to get the proper types after the parameters have passed through validation.call- The inferred input type from the compiled validator. This should be used withbroker.callorctx.callas the second type parameter to get proper types for the action call.validator- The compiled validator.return- The types provided in thereturnTypeargument when the instance was constructed. If none were provided, this defaults to a type ofanyinstead.
// It's easier to set up your validator objects outside of the service constructor so you can more easily access the typings later.
const simpleValidator = new ZodParams({
string: z.string(),
number: z.number(),
optional: z.any().optional()
});
const complexValidator = new ZodParams({
string: z.string(),
number: z.number(),
object: z.object({
nestedString: z.string(),
nestedBoolean: z.boolean()
})
}, {
partial: true,
catchall: z.number()
}});
broker.createService({
name: "example",
actions: {
simpleExample: {
params: simpleValidator.schema,
handler(ctx: Context<typeof simpleValidator.context>) { ... }
},
complexExample: {
params: complexValidator.schema,
handler(ctx: Context<typeof complexExample.context>) { ... }
}
}
});
// ...
broker.call<
typeof simpleValidator.return,
typeof simpleValidator.call
>({ string: "yes", number: 42 }); // calls successfully
broker.call<
typeof complexValidator.return,
typeof complexValidator.call
>({
object: {
nestedString: "not optional",
nestedBoolean: false
},
unrecognizedKey: 69
}); // throws ValidationError