我尝试在我的项目中使用mongoose,graphql和next.js,但是一直收到这个错误:
Error: You try to generate GraphQL Type with name Customer from mongoose model but this type already exists in SchemaComposer. Please choose another type name "composeWithMongoose(model, { name: 'NewTypeName' })", or reuse existed type "schemaComposer.getOTC('TypeName')", or remove type from SchemaComposer before calling composeWithMongoose method "schemaComposer.delete('TypeName')".我所拥有的是简单的mongoose模式:
const mongoose = require('mongoose');
const CustomerSchema = new mongoose.Schema({
name: {
type: String
}
}, {
toJSON: {
transform: function (doc, ret, options) {
ret.id = ret._id.toString();
delete ret.__v;
delete ret._id;
}
}
});和组成gql模式的单独模块:
import {composeMongoose} from "graphql-compose-mongoose";
import { schemaComposer } from 'graphql-compose';
import {Customer} from '../db/models/Customer';
const customizationOptions = {}
const CustomerTC = composeMongoose(Customer, customizationOptions);
schemaComposer.Query.addFields({
customerById: CustomerTC.mongooseResolvers.findById()
})
console.log("Schema:", schemaComposer.getOTC('Customer'))
const customerSchema = schemaComposer.buildSchema();
export default customerSchema;和服务器api模块:
import {ApolloServer} from 'apollo-server-micro'
import customerSchema from '../../apollo/customer-type-defs';
const apolloServer = new ApolloServer({
schema: customerSchema,
context: () => ({})
});
export const config = {
api: {
bodyParser: false,
},
}
export default apolloServer.createHandler({path: '/api/graphql'})有没有人能告诉我如何修复这个错误?
发布于 2021-04-17 18:17:43
我遇到了同样的问题,我发现解决方案只是简单地检查ObjectTC是否已经存在,如果不存在就创建它。
function createObjectTC({ model, customizationOptions = {} }}) {
let ModelTC = null;
try {
ModelTC = schemaComposer.getOTC(model.modelName);
} catch {
ModelTC = composeWithMongoose(model, customizationOptions);
}
return ModelTC;
}
const UserTC = createObjectTC({ model: User, customizationOptions: {} });发布于 2021-07-26 17:41:48
我的解决方案是用graphql和express创建一个单独的后端服务器。以及前端服务器,以保持由下一服务器引擎提供的所有内置优点。技巧是设置一个api/graphql端点,将graphql调用转发到后端服务器。
下面是我的api端点:
/api/raphql.js
import logger from '../../lib/logger'
import {getSession} from "next-auth/client";
export default async (_req, _res) => {
// logger.debug("api/graphql: Request body:\n", _req.body)
const session = await getSession({req: _req})
logger.debug( "current session: ", session )
const accessToken = session?.accessToken ?? "";
const query = {
method: 'POST', // *GET, POST, PUT, DELETE, etc.
mode: 'cors', // no-cors, *cors, same-origin
cache: 'no-cache', // *default, no-cache, reload, force-cache, only-if-cached
credentials: 'same-origin', // include, *same-origin, omit
headers: {
'Content-Type': 'application/json',
'infraToken': session.infraToken
// 'Content-Type': 'application/x-www-form-urlencoded',
},
redirect: 'follow', // manual, *follow, error
referrerPolicy: 'no-referrer', // no-referrer, *no-referrer-when-downgrade, origin, origin-when-cross-origin, same-origin, strict-origin, strict-origin-when-cross-origin, unsafe-url
body: JSON.stringify({
operationName: _req.body.operationName,
variables: _req.body.variables,
query: _req.body.query
}) // body data type must match "Content-Type" header
};
const res = await fetch('http://localhost:4000/api/graphql', query)
const json = await res.json()
_res.statusCode = 200;
_res.setHeader('Content-Type', 'application/json');
_res.setHeader('Cache-Control', 'max-age=180000');
_res.json(json)
_res.end()
};i还有其他端点来处理rest操作,如图像上传和获取。和认证分别在/api/rest/...rest.js和/api/auth/...nextauth.js
下
https://stackoverflow.com/questions/65363379
复制相似问题