【发布时间】:2020-10-16 07:47:24
【问题描述】:
我很确定由于我导入和导出 mongoose 模式的方式而出现此错误,并且我已经在 Node 中完成了此操作,但是尝试将我的代码转换为 TypeScript 给了我一些成长的痛苦。
初始运行完全正常,我得到了我正在寻找的 GraphQL 操场。但是,如果我稍微修改我的代码库,我就会在标题中看到错误。
模型\User.ts
import { Schema, Document, Model, model } from 'mongoose';
export interface IUser extends Document {
name: string;
email: string;
password: string;
}
//Create Schema
const UserSchema: Schema = new Schema({
name: {
type: String,
required: true
},
email: {
type: String,
required: true
},
password: {
type: String,
required: true
}
});
export const User: Model<IUser> = model<IUser>('User', UserSchema);
模型\index.ts
import { User } from "./User";
export default {
User
};
lambda\graphql.ts
import { ApolloServer, AuthenticationError } from "apollo-server-lambda";
import "reflect-metadata";
import resolvers from "../resolvers";
import schemas from "../schema";
import * as mongoose from "mongoose";
import { verify } from "jsonwebtoken";
import models from "../models";
import { MONGODB_URI, SECRET } from "../utils/constants";
export interface IToken extends Document {
name: string;
email: string;
password: string;
}
//validate jwt then set me in graphql server context
const getMe = async (token: any) => {
if (token) {
try {
const user = await verify(token, SECRET)
return user;
} catch (e) {
throw new AuthenticationError("Your Session expired. Sign in again.");
}
}
return null;
};
const server = new ApolloServer({
typeDefs: schemas,
resolvers,
context: async ({ event }) => {
const user = await getMe(event.headers.authorization);
return {
models,
me: user,
secret: SECRET
}
}
});
mongoose
.connect(MONGODB_URI, { 'useUnifiedTopology': true, 'useNewUrlParser': true })
.then(() => {
console.log("mongodb connected");
})
.catch(err => {
console.log(err);
});
exports.handler = server.createHandler({
cors: {
origin: "*",
credentials: true
}
});
我怀疑这是我在 models\index.ts 中导入的方式?我错过了什么?
【问题讨论】:
-
您是否使用了 mannieschumpert 建议的解决方案,或者您是否找到了解决此问题的其他方法?
标签: typescript mongoose lambda