我在 GraphQL Pothos Builder 中创建了一个登录组件。我使用 Prisma 作为我的 ORM。我想知道如何发送自定义输出作为响应。目前我只能发送用户类型的响应。我尝试创建 UserAndToken ObjectRef 但它似乎不起作用。你能帮我解决这个错误吗?过去一周我一直在努力,但我一直坚持这一点。预先感谢。
import prisma from "@/prisma/client";
import { User as UserModel } from "@prisma/client";
import bcrypt from "bcrypt";
import { GraphQLError } from "graphql";
import ms from "ms";
import { cookies } from "next/headers";
import { builder } from "../builder";
import { User } from "../types/User";
import {
generateAccessToken,
generateRefreshToken,
} from "../utils/generateToken";
const UserAndToken = builder
.objectRef<{ user: UserModel, accessToken: string }>("UserAndToken")
.implement({
fields: t => ({
user: t.field({ type: User, resolve: (parent) => parent.user })
})
})
builder.mutationFields((t) => ({
login: t.prismaField({
description: "Login to time boxing platform.",
type: UserAndToken,
args: {
email: t.arg({ type: "Email", required: true }),
password: t.arg.string({ required: true }),
},
resolve: async (query, _, args) => {
const user = await prisma.user.findUnique({
where: { email: args.email },
});
if (
!user ||
!bcrypt.compare(args.password, user.password)
) {
return Promise.reject(
new GraphQLError(
"Either email or password is incorrect."
)
);
}
try {
const accessToken = generateAccessToken(user);
const refreshToken = generateRefreshToken(user);
cookies().set({
name: "X-REFRESH-TOKEN",
value: refreshToken,
httpOnly: true,
sameSite: process.env.NODE_ENV === "production" ? "none" : "lax",
secure: process.env.NODE_ENV === "production",
expires: new Date(Date.now() + ms("7d")), //7d
});
await prisma.session.create({
data: {
refreshToken,
expiresAt: new Date(new Date().getDate() + 7),
userId: user.id,
},
});
// update user's last login.
await prisma.user.update({
where: { id: user.id },
data: { lastLogin: new Date() },
});
return { user, accessToken };
} catch (err) {
console.log(err)
return Promise.reject(
new GraphQLError(
"Unable to login. Try again later."
)
);
}
},
}),
}));
我尝试根据本文创建一个 ObjectRef,但它对我不起作用。这是该文章的链接 - https://github.com/hayes/pothos/discussions/1032
const UserAndToken = builder
.objectRef<{ user: UserModel, accessToken: string }>("UserAndToken")
.implement({
fields: t => ({
user: t.field({ type: User, resolve: (parent) => parent.user })
})
})
您需要将
t.prismaField
更改为 t.field
才能自定义响应选项。
安装 SimpleObjectsPlugin。
npm i @pothos/plugin-simple-objects
将该插件添加到 SchemaBuilder。
plugins: [PrismaPlugin, SimpleObjectsPlugin],
prisma: {
client: prisma,
},
});```
在构建器对象中添加来自 Prisma Client 的用户对象。
PrismaTypes: PrismaTypes;
Scalars: {
DateTime: {
Input: DateTime;
Output: DateTime;
};
Email: {
Input: string;
Output: string;
};
};
Objects: {
User: User
}
};```
创建一个LoginResponse SimpleObject并将类型更改为LoginResponse
fields: (t) => ({
user: t.field({ type: "User" }),
accessToken: t.string({})
})
})```