New Case Study:See how Anthropic automated 95% of dependency reviews with Socket.Learn More
Socket
Sign inDemoInstall
Socket

moleculer-zod-validator

Package Overview
Dependencies
Maintainers
1
Versions
10
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

moleculer-zod-validator

A validator for the Moleculer microservice framework to allow the use of Zod.

  • 3.0.0
  • Source
  • npm
  • Socket score

Version published
Weekly downloads
1.5K
increased by39.17%
Maintainers
1
Weekly downloads
 
Created
Source

moleculer-zod-validator

Validate Moleculer action parameters using the Zod validator.

Continuous Integration npm version downloads

Supports

  • Supports Moleculer v0.14.x
  • Supports Zod v3.x.x

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 or two arguments, schema and optionally options.

  • schema - This is a schema object that gets passed directly into z.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 to false except for strip, which is implicitly set to true.
    • 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 with passthrough and strict, and will override them if set. (docs)
    • passthrough (boolean) - Passes through unrecognized keys. Mutually exclusive with strict and strip. (docs)
    • strict (boolean) - Throws an error if unrecognized keys are present. Mutually exclusive with passthrough and strip. (docs)
    • catchall (Zod validator) - Validates all unknown keys against this schema. Obviates strict, passthrough, and strip. (docs)

Additionally, support for object transformations is present, allowing for the use of features such as preprocessing, refinements, transforms, and defaults.

Once constructed, there are four properties exposed on the ZodParams object.

  • schema - The raw schema passed in. This should be passed to the params object in the action definition.
  • context - The inferred output type from the compiled validator. This should be used within the Context object 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 with broker.call or ctx.call as the second type parameter to get proper types for the action call.
  • validator - The compiled validator.
// 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<
    ReturnType, 
    typeof simpleValidator.call
>({ string: "yes", number: 42 }); // calls successfully

broker.call<
    ReturnType, 
    typeof complexValidator.call
>({
    object: { 
        nestedString: "not optional", 
        nestedBoolean: false 
    }, 
    unrecognizedKey: 69 
}); // throws ValidationError

Keywords

FAQs

Package last updated on 14 Apr 2023

Did you know?

Socket

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc