【发布时间】:2020-09-26 11:30:29
【问题描述】:
您好,我正在尝试返回自定义错误 用户创建的示例并且电子邮件存在:
{
"errors": [
{
"message": "The email exists",
"statusCode": "400"
}
],
"data": null
}
我现在有这个:
我的 APP.TS:
export async function startServer() {
const app = express();
const schema = await createSchema();
useContainer(Container);
const connection = await createConnection();
const server = new ApolloServer({
schema,
context: ({ req, res }: any) => ({ req, res }),
});
server.applyMiddleware({ app });
return app;
}
Resovler.TS:
@Resolver()
export class CreateUserResolver {
//dependency inject
constructor(private readonly userService: UserService) {}
//create User Mutaton
@Mutation(() => User)
async register(
@Arg('data')
data: RegisterInput,
): Promise<Partial<User> | Object> {
const user = this.userService.findOrCreate(data);
return user;
}
}
输入:
@InputType()
export class RegisterInput {
@Field()
@IsEmail({}, { message: 'Invalid email' })
email: string;
@Field()
@Length(1, 255)
name: string;
@Field()
password: string;
}
服务:
constructor(
@InjectRepository(User)
private userRep: Repository<User>,
) {}
async findOrCreate(data: Partial<User>): Promise<Partial<User> | Object> {
let user = await this.userRep.findOne({ where: { email: data.email } });
if (user) throw new Error('user already exists');
data.password = await bcrypt.hash(data.password, 12);
user = await this.userRep.save({
...data,
});
return user;
}
目前我找到的唯一解决方案是使用:
if (user) throw new Error ('user already exists');
但我无法想象如何使用状态码或只返回错误消息而不是所有这些消息:
【问题讨论】:
标签: typescript graphql typeorm