zod#z TypeScript Examples

The following examples show how to use zod#z. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: util.ts    From linear-discord-serverless with MIT License 7 votes vote down vote up
createAllStates = <T extends AnyZodObject, R extends AnyZodObject>(
	commons: T,
	removeState: R,
) => {
	return z
		.object({
			action: z.enum([Action.UPDATE, Action.CREATE]),
			data: commons,
		})
		.or(
			z.object({
				action: z.literal(Action.REMOVE),
				data: removeState.merge(commons),
			}),
		);
}
Example #2
Source File: schemas.ts    From keycaplendar with MIT License 6 votes vote down vote up
VendorSchema = schemaForType<VendorType>()(
  z.object({
    endDate: z.string().optional(),
    id: z.string(),
    name: z.string().min(1),
    region: z.string().min(1),
    storeLink: allowEmpty(z.string().url()),
  })
)
Example #3
Source File: types.ts    From backstage with Apache License 2.0 6 votes vote down vote up
samlSessionSchema: z.ZodSchema<SamlSession> = z.object({
  profile: z.object({
    email: z.string().optional(),
    displayName: z.string().optional(),
    picture: z.string().optional(),
  }),
  backstageIdentity: z.object({
    token: z.string(),
    identity: z.object({
      type: z.literal('user'),
      userEntityRef: z.string(),
      ownershipEntityRefs: z.array(z.string()),
    }),
  }),
})
Example #4
Source File: receipt.ts    From airnode with MIT License 6 votes vote down vote up
receiptSchema = z
  .object({
    airnodeWallet: airnodeWalletSchema,
    deployment: deploymentSchema,
    api: apiSchema,
  })
  .strict()
  .superRefine(({ airnodeWallet, deployment }, ctx) => {
    // TODO: There's no need to have Arnode short address twice in the receipt.json
    if (airnodeWallet.airnodeAddressShort !== deployment.airnodeAddressShort) {
      ctx.addIssue({
        code: z.ZodIssueCode.custom,
        message: `Airnode short addresses don't match`,
        path: ['airnodeWallet', 'airnodeAddressShort'],
      });
    }
  })
Example #5
Source File: notionPageSeoSchema.ts    From pagely with MIT License 6 votes vote down vote up
notionPageSeoSchema = z.object({
  siteName: z
    .string()
    .min(1, 'Name must be at least 1 character long.')
    .max(100, 'Name must be less than 100 characters long.')
    .nonempty('Please enter a name for the site.'),
  siteDesc: z
    .string()
    .min(1, 'Description must be at least 1 character long.')
    .max(100, 'Description must be less than 100 characters long.')
    .nonempty('Please fill in the description.')
    .optional(),
  ogImageUrl: z.string().optional(),
})
Example #6
Source File: api-response.ts    From express-zod-api with MIT License 6 votes vote down vote up
createApiResponse = <S extends z.ZodTypeAny>(
  schema: S,
  mimeTypes: MimeDefinition = mimeJson
) => {
  return {
    schema,
    mimeTypes: typeof mimeTypes === "string" ? [mimeTypes] : mimeTypes,
  } as ApiResponse<S>;
}
Example #7
Source File: receipt.ts    From airnode with MIT License 6 votes vote down vote up
deploymentSchema = z
  .object({
    nodeVersion: z.string().superRefine((version, ctx) => {
      if (version === packageVersion) return;

      ctx.addIssue({
        code: z.ZodIssueCode.custom,
        message: `The "nodeVersion" must be ${packageVersion}`,
        path: [],
      });
    }),
    airnodeAddressShort: z.string(),
    stage: z.string().regex(/^[a-z0-9-]{1,16}$/),
    cloudProvider: cloudProviderSchema,
    timestamp: z.string().regex(ISO_DATE_REGEX),
  })
  .strict()
Example #8
Source File: endpoint.ts    From express-zod-api with MIT License 6 votes vote down vote up
async #parseOutput(output: any) {
    try {
      return await this.outputSchema.parseAsync(output);
    } catch (e) {
      if (e instanceof z.ZodError) {
        throw new z.ZodError([
          {
            message: "Invalid format",
            code: "custom",
            path: ["output"],
          },
          ...e.issues.map((issue) => ({
            ...issue,
            path: issue.path.length === 0 ? ["output"] : issue.path,
          })),
        ]);
      }
      throw e;
    }
  }
Example #9
Source File: ois.ts    From airnode with MIT License 6 votes vote down vote up
oisSchema = z
  .object({
    oisFormat: z.string(),
    title: z.string(),
    version: z.string(),
    apiSpecifications: apiSpecificationSchema,
    endpoints: z.array(endpointSchema),
  })
  .strict()
  .superRefine(ensureSingleParameterUsagePerEndpoint)
  .superRefine(ensureEndpointAndApiSpecificationParamsMatch)
Example #10
Source File: endpoints-factory.ts    From express-zod-api with MIT License 6 votes vote down vote up
public addExpressMiddleware<
    R extends Request,
    S extends Response,
    AOUT extends FlatObject = {}
  >(
    middleware: ExpressMiddleware<R, S>,
    features?: ExpressMiddlewareFeatures<R, S, AOUT>
  ) {
    const transformer = features?.transformer || ((err: Error) => err);
    const provider = features?.provider || (() => ({} as AOUT));
    const definition = createMiddleware({
      input: z.object({}),
      middleware: async ({ request, response }) =>
        new Promise<AOUT>((resolve, reject) => {
          const next = (err?: any) => {
            if (err && err instanceof Error) {
              return reject(transformer(err));
            }
            resolve(provider(request as R, response as S));
          };
          middleware(request as R, response as S, next);
        }),
    });
    return EndpointsFactory.#create<POS, NEG, IN, OUT & AOUT>(
      this.middlewares.concat(definition as AnyMiddlewareDef),
      this.resultHandler
    );
  }
Example #11
Source File: ois.ts    From airnode with MIT License 6 votes vote down vote up
endpointSchema = z
  .object({
    description: z.string().optional(),
    externalDocs: z.string().optional(),
    fixedOperationParameters: z.array(fixedParameterSchema),
    name: z.string(),
    operation: endpointOperationSchema,
    parameters: z.array(endpointParameterSchema),
    preProcessingSpecifications: z.array(processingSpecificationSchema).optional(),
    postProcessingSpecifications: z.array(processingSpecificationSchema).optional(),
    reservedParameters: z.array(reservedParameterSchema),
    summary: z.string().optional(),
  })
  .strict()
Example #12
Source File: open-api-helpers.ts    From express-zod-api with MIT License 6 votes vote down vote up
depictDiscriminatedUnion: DepictHelper<
  z.ZodDiscriminatedUnion<string, z.Primitive, z.ZodObject<any>>
> = ({ schema: { options, discriminator }, initial, isResponse }) => {
  return {
    ...initial,
    discriminator: {
      propertyName: discriminator,
    },
    oneOf: Array.from(options.values()).map((option) =>
      depictSchema({ schema: option, isResponse })
    ),
  };
}
Example #13
Source File: ois.ts    From airnode with MIT License 6 votes vote down vote up
apiSpecificationSchema = z
  .object({
    components: apiComponentsSchema,
    paths: pathsSchema,
    servers: z.array(serverSchema),
    security: z.record(z.tuple([])),
  })
  .strict()
  .superRefine((apiSpecifications, ctx) => {
    Object.keys(apiSpecifications.security).forEach((enabledSecuritySchemeName, index) => {
      // Verify that ois.apiSpecifications.security.<securitySchemeName> is
      // referencing a valid ois.apiSpecifications.components.<securitySchemeName> object
      const enabledSecurityScheme = apiSpecifications.components.securitySchemes[enabledSecuritySchemeName];
      if (!enabledSecurityScheme) {
        ctx.addIssue({
          code: z.ZodIssueCode.custom,
          message: `Security scheme "${enabledSecuritySchemeName}" is not defined in "components.securitySchemes"`,
          path: ['security', index],
        });
      }
    });
  })
Example #14
Source File: open-api-helpers.ts    From express-zod-api with MIT License 6 votes vote down vote up
depictArray: DepictHelper<z.ZodArray<z.ZodTypeAny>> = ({
  schema: { _def: def },
  initial,
  isResponse,
}) => ({
  ...initial,
  type: "array",
  items: depictSchema({ schema: def.type, isResponse }),
  ...(def.minLength ? { minItems: def.minLength.value } : {}),
  ...(def.maxLength ? { maxItems: def.maxLength.value } : {}),
})
Example #15
Source File: config.ts    From airnode with MIT License 6 votes vote down vote up
priorityFeeSchema = z
  .object({
    value: z.number(),
    unit: z
      .union([
        z.literal('wei'),
        z.literal('kwei'),
        z.literal('mwei'),
        z.literal('gwei'),
        z.literal('szabo'),
        z.literal('finney'),
        z.literal('ether'),
      ])
      .optional(),
  })
  .strict()
Example #16
Source File: meta.test.ts    From zod-to-json-schema with ISC License 6 votes vote down vote up
describe("Meta data", () => {
  it("should be possible to use description", () => {
    const $z = z.string().describe("My neat string");
    const $j = zodToJsonSchema($z);
    const $e: JSONSchema7 = {
      $schema: "http://json-schema.org/draft-07/schema#",
      type: "string",
      description: "My neat string",
    };

    expect($j).toStrictEqual($e);
  });
});
Example #17
Source File: ois.ts    From airnode with MIT License 6 votes vote down vote up
apiSecuritySchemeSchema = z.discriminatedUnion('type', [
  apiKeySecuritySchemeSchema,
  httpSecuritySchemeSchema,
  relayChainIdSecuritySchemeSchema,
  relayChainTypeSecuritySchemeSchema,
  relayRequesterAddressSecuritySchemeSchema,
  relaySponsorAddressSecuritySchemeSchema,
  relaySponsorWalletAddressSecuritySchemeSchema,
])
Example #18
Source File: effects.test.ts    From zod-to-json-schema with ISC License 6 votes vote down vote up
describe("effects", () => {
  it("should be possible to use refine", () => {
    const parsedSchema = parseEffectsDef(
      z.number().refine((x) => x + 1)._def,
      new References()
    );
    const jsonSchema: JSONSchema7Type = {
      type: "number",
    };
    expect(parsedSchema).toStrictEqual(jsonSchema);
  });

  it("should default to the input type", () => {
    const schema = z.string().transform((arg) => parseInt(arg));

    const jsonSchema = parseEffectsDef(schema._def, new References());

    expect(jsonSchema).toStrictEqual({
      type: "string",
    });
  });

  it("should default to any if given that effectStrategy", () => {
    const schema = z.string().transform((arg) => parseInt(arg));

    const jsonSchema = parseEffectsDef(
      schema._def,
      new References(undefined, undefined, undefined, "any")
    );

    expect(jsonSchema).toStrictEqual({});
  });
});
Example #19
Source File: util.ts    From linear-discord-serverless with MIT License 6 votes vote down vote up
defaultRemoveSchema = z.object({archivedAt: dateResolvable})
Example #20
Source File: object.test.ts    From zod-to-json-schema with ISC License 6 votes vote down vote up
describe("objects", () => {
  it("should be possible to describe catchAll schema", () => {
    const schema = z
      .object({ normalProperty: z.string() })
      .catchall(z.boolean());

    const parsedSchema = parseObjectDef(schema._def, new References());
    const expectedSchema = {
      type: "object",
      properties: {
        normalProperty: { type: "string" },
      },
      required: ["normalProperty"],
      additionalProperties: {
        type: "boolean",
      },
    };
    expect(parsedSchema).toStrictEqual(expectedSchema);
  });

  it("should be possible to use selective partial", () => {
    const schema = z
      .object({ foo: z.boolean(), bar: z.number() })
      .partial({ foo: true });

    const parsedSchema = parseObjectDef(schema._def, new References());
    const expectedSchema = {
      type: "object",
      properties: {
        foo: { type: "boolean" },
        bar: { type: "number" },
      },
      required: ["bar"],
      additionalProperties: false,
    };
    expect(parsedSchema).toStrictEqual(expectedSchema);
  });
});
Example #21
Source File: config.ts    From airnode with MIT License 6 votes vote down vote up
chainConfigSchema = z
  .object({
    authorizers: z.array(z.string()),
    blockHistoryLimit: z.number().optional(),
    contracts: chainContractsSchema,
    id: z.string(),
    minConfirmations: z.number().optional(),
    type: chainTypeSchema,
    options: chainOptionsSchema,
    providers: z.record(providerSchema),
    maxConcurrency: z.number(),
  })
  .strict()
Example #22
Source File: promise.test.ts    From zod-to-json-schema with ISC License 6 votes vote down vote up
describe("promise", () => {
  it("should be possible to use promise", () => {
    const parsedSchema = parsePromiseDef(
      z.promise(z.string())._def,
      new References()
    );
    const jsonSchema: JSONSchema7Type = {
      type: "string",
    };
    expect(parsedSchema).toStrictEqual(jsonSchema);
  });
});
Example #23
Source File: reaction.ts    From linear-discord-serverless with MIT License 6 votes vote down vote up
commons = z.object({
	id: z.string().uuid(),
	createdAt: dateResolvable,
	updatedAt: dateResolvable,
	emoji: z.string(),
	userId: z.string().uuid(),
	commentId: z.string().uuid(),
	comment: z.object({
		id: z.string().uuid(),
		body: z.string(),
		userId: z.string().uuid(),
	}),
	user: z.object({
		id: z.string().uuid(),
		name: z.string(),
	}),
})
Example #24
Source File: tuple.test.ts    From zod-to-json-schema with ISC License 6 votes vote down vote up
describe("objects", () => {
  it("should be possible to describe a simple tuple schema", () => {
    const schema = z.tuple([z.string(), z.number()]);

    const parsedSchema = parseTupleDef(schema._def, new References());
    const expectedSchema = {
      type: "array",
      items: [{ type: "string" }, { type: "number" }],
      minItems: 2,
      maxItems: 2,
    };
    expect(parsedSchema).toStrictEqual(expectedSchema);
  });

  it("should be possible to describe a tuple schema with rest()", () => {
    const schema = z.tuple([z.string(), z.number()]).rest(z.boolean());

    const parsedSchema = parseTupleDef(schema._def, new References());
    const expectedSchema = {
      type: "array",
      items: [{ type: "string" }, { type: "number" }],
      minItems: 2,
      additionalItems: {
        type: "boolean",
      },
    };
    expect(parsedSchema).toStrictEqual(expectedSchema);
  });
});
Example #25
Source File: project.ts    From linear-discord-serverless with MIT License 6 votes vote down vote up
commons = z.object({
	id: z.string().uuid(),
	createdAt: dateResolvable,
	updatedAt: dateResolvable,
	name: z.string(),
	description: z.string(),
	slugId: z.string(),
	color: z.string(),
	state: z.string(),
	creatorId: z.string().uuid(),
	sortOrder: z.number(),
	// TODO(@alii): Find out the type for these arrays
	issueCountHistory: z.array(z.unknown()),
	completedIssueCountHistory: z.array(z.unknown()),
	scopeHistory: z.array(z.unknown()),
	completedScopeHistory: z.array(z.unknown()),
	slackIssueComments: z.boolean(),
	slackIssueStatuses: z.boolean(),
	teamIds: z.array(z.string().uuid()),
	// TODO(@alii): Find out this type
	memberIds: z.array(z.unknown()),
})
Example #26
Source File: zodToJsonSchema.test.ts    From zod-to-json-schema with ISC License 6 votes vote down vote up
describe("Root schema result after parsing", () => {
  it("should return the schema directly in the root if no name is passed", () => {
    expect(zodToJsonSchema(z.any())).toStrictEqual({
      $schema: "http://json-schema.org/draft-07/schema#",
    });
  });
  it('should return the schema inside a named property in "definitions" if a name is passed', () => {
    expect(zodToJsonSchema(z.any(), "MySchema")).toStrictEqual({
      $schema: "http://json-schema.org/draft-07/schema#",
      $ref: `#/definitions/MySchema`,
      definitions: {
        MySchema: {},
      },
    });
  });

  it('should return the schema inside a named property in "$defs" if a name and definitionPath is passed in options', () => {
    expect(
      zodToJsonSchema(z.any(), { name: "MySchema", definitionPath: "$defs" })
    ).toStrictEqual({
      $schema: "http://json-schema.org/draft-07/schema#",
      $ref: `#/$defs/MySchema`,
      $defs: {
        MySchema: {},
      },
    });
  });
});
Example #27
Source File: issue.ts    From linear-discord-serverless with MIT License 6 votes vote down vote up
commons = z.object({
	id: z.string().uuid(),
	createdAt: dateResolvable,
	updatedAt: dateResolvable,
	number: z.number().positive(),
	title: z.string(),
	description: z.string(),
	priority: z.number(),
	boardOrder: z.number(),
	sortOrder: z.number(),
	previousIdentifiers: z.array(z.string()),
	priorityLabel: z.string(),
	teamId: z.string().uuid(),
	stateId: z.string().uuid(),
	assigneeId: z.string().uuid().optional(),
	subscriberIds: z.array(z.string().uuid()),
	creatorId: z.string().uuid(),
	labelIds: z.array(z.string().uuid()),
	state,
	team,
	labels: z.array(label).optional(),
})
Example #28
Source File: ois.ts    From airnode with MIT License 6 votes vote down vote up
endpointParameterSchema = z
  .object({
    name: z.string(),
    operationParameter: operationParameterSchema,
    default: z.string().optional(),
    description: z.string().optional(),
    example: z.string().optional(),
    required: z.boolean().optional(),
  })
  .strict()
Example #29
Source File: schemas.ts    From keycaplendar with MIT License 6 votes vote down vote up
GuideEntrySchema = schemaForType<GuideEntryType>()(
  z.object({
    body: z.string().min(1),
    description: z.string().min(1),
    id: z.string().min(1),
    name: z.string().min(1),
    tags: z.string().min(1).array(),
    title: z.string().min(1),
    visibility: z.enum(visibilityVals),
  })
)