zod-graphql-type 中文文档教程
zod-graphql-type
ZodError
GraphQL 类型,以便您可以返回 zod
GraphQL API 中的错误。
作为示例用例,我们假设您有一个 GraphQL 突变,可以将用户登录到您的应用程序中。该突变接受 Google oAuth 令牌来对用户进行身份验证。 GraphQL 可以确保突变上的输入类型是正确的。但是,在 GraphQL 解析器中,您需要验证 oAuth 令牌的完整性。验证令牌的完整性后,您可以使用 zod 模式验证令牌对象。该包允许您将 zod 抛出的任何错误返回给您的 API 使用者,以获得清晰的错误详细信息。
这个包为您提供了 3 个东西:
- ZodError 类型定义,可导入到您的 GraphQL 架构中以用于其他类型;
- 自定义 GraphQL 解析器以使 ZodError 类型定义起作用;
- formatErrors
zodErrorsTozodIssues
函数,用于将 ZodError(其中有Error
对象,因此不能很好地与 GraphQL 配合使用)转换为 ZodIssues(没有Error
对象) )。
入门
安装
npm install zod-zod-graphql-type
用法
import { zodTypeDef } from "zod-graphql-type";
然后将类型定义添加到您的 GraphQL 类型架构中。
以下是 Fastify Mercurius 示例:
import { Fastify } from "fastify";
import mercurius from "mercurius";
import { z } from "zod";
import { zodTypeDef, scalars, zodErrorsTozodIssues } from "zod-graphql-type";
const fastify = Fastify();
const schema = `
${zodTypeDef},
input ObjectToValidate {
phraseFirstHalf: String
}
type Success {
message: String!
}
type Error {
message: String!
zodIssues: [ZodIssue]
}
type Query {
validatePhrase(input: ObjectToValidate): Success | Error
}
`;
const resolvers = {
Query: {
validatePhrase: (_, { phrase }) => {
const phraseSecondHalf = fetch(`https://someapi.com?phrase=${phrase}`);
// Create a zod schema to validate the argument
const schema = z.object({
phrase: z.literal("world"),
});
try {
schema.parse(phraseSecondHalf);
return {
__typename: "Success",
message: "Object passed validation.",
};
} catch (error) {
return {
__typename: "Error",
message: "Object failed vlaidation.",
zodIssues: zodErrorsTozodIssues(error),
};
}
},
},
};
app.register(mercurius, {
schema,
resolvers,
});
app.get("/", async function (req, reply) {
const query = '{ validatePhrase(input: {phraseFirstHalf: "world"})}';
return reply.graphql(query);
});
app.listen({ port: 3000 });
请注意,您需要使用 formatErrors
函数,该函数将 ZodError
替换为 ZodIssue[]
。 ZodError
的类型为 Error
,如果您向 GraphQL 返回 Error
类型,它将不允许您正确返回 ZodIssues。
特性
绝大多数 ZodError 类型都经过测试并且可以工作。以下内容经过测试:
ZodIssueCode.invalid_type
ZodIssueCode.unrecognized_keys
ZodIssueCode.invalid_union
ZodIssueCode.invalid_enum_value
ZodIssueCode。 Too_big
ZodIssueCode.too_small
ZodIssueCode.invalid_type =>自定义错误
ZodIssueCode.invalid_string
ZodIssueCode.invalid_date
ZodIssueCode.not_multiple_of
已知以下内容尚无法工作(可以在未来):
ZodIssueCode.invalid_arguments
由z.function().args().implement()
产生的错误ZodIssueCode.invalid_return_type
一个错误由z.function().returnType().implement()
生成
除了使用 .implement()
z.function() 函数架构之外的所有内容代码>应该可以正常工作。如果您发现错误,请创建问题。
注释
这还不是 1.0.0 版本。由于该功能正在积极开发中,因此版本控制在 1.0.0 之前不会遵循 SEMVER。
zod-graphql-type
ZodError
GraphQL type so that you can return zod
errors in your GraphQL API.
As an example use case, let's assume you have a GraphQL mutation that signs a user into your application. The mutation accepts a Google oAuth token to authenticate the user. GraphQL can ensure the input types on the mutation are correct. However, in your GraphQL resolver, you will want to verify the integrity of the oAuth token. Once you verify the integrity of the token, you can validate the token object with a zod schema. This package allows you to return any errors that zod throws for crystal clear error detail to your API consumer.
This package gives you 3 things:
- A ZodError type definition to import into your GraphQL schema for use in other types;
- Custom GraphQL resolvers to make the ZodError type definition work;
- A formatErrors
zodErrorsTozodIssues
function to transform ZodError (hasError
objects in it so it doesn't work with GraphQL nicely) into ZodIssues (noError
object).
Getting started
Installation
npm install zod-zod-graphql-type
Usage
import { zodTypeDef } from "zod-graphql-type";
Then add the type definition to your GraphQL type schema.
Here is a Fastify Mercurius example:
import { Fastify } from "fastify";
import mercurius from "mercurius";
import { z } from "zod";
import { zodTypeDef, scalars, zodErrorsTozodIssues } from "zod-graphql-type";
const fastify = Fastify();
const schema = `
${zodTypeDef},
input ObjectToValidate {
phraseFirstHalf: String
}
type Success {
message: String!
}
type Error {
message: String!
zodIssues: [ZodIssue]
}
type Query {
validatePhrase(input: ObjectToValidate): Success | Error
}
`;
const resolvers = {
Query: {
validatePhrase: (_, { phrase }) => {
const phraseSecondHalf = fetch(`https://someapi.com?phrase=${phrase}`);
// Create a zod schema to validate the argument
const schema = z.object({
phrase: z.literal("world"),
});
try {
schema.parse(phraseSecondHalf);
return {
__typename: "Success",
message: "Object passed validation.",
};
} catch (error) {
return {
__typename: "Error",
message: "Object failed vlaidation.",
zodIssues: zodErrorsTozodIssues(error),
};
}
},
},
};
app.register(mercurius, {
schema,
resolvers,
});
app.get("/", async function (req, reply) {
const query = '{ validatePhrase(input: {phraseFirstHalf: "world"})}';
return reply.graphql(query);
});
app.listen({ port: 3000 });
Note that you will need to use the formatErrors
function which replaces ZodError
with ZodIssue[]
. ZodError
is of type Error
and if you return a type of Error
to GraphQL it will not allow you to return the ZodIssues properly.
Features
The vast majority of ZodError types are tested and working. The following are tested:
ZodIssueCode.invalid_type
ZodIssueCode.unrecognized_keys
ZodIssueCode.invalid_union
ZodIssueCode.invalid_enum_value
ZodIssueCode.too_big
ZodIssueCode.too_small
ZodIssueCode.invalid_type => custom error
ZodIssueCode.invalid_string
ZodIssueCode.invalid_date
ZodIssueCode.not_multiple_of
The following are known to not work yet (support could be added in the future):
ZodIssueCode.invalid_arguments
an error produced fromz.function().args().implement()
ZodIssueCode.invalid_return_type
an error produced fromz.function().returnType().implement()
Everything other than z.function()
function schemas that use .implement()
should be working properly. If you find a bug, please create an issue.
Notes
This is not yet a 1.0.0 release. Since this is under active development, versioning won't follow SEMVER until 1.0.0.