感谢其他答案,这是针对Nextjs中的getServerSideProps、getStaticProps、getStaticPaths和getStaticProps,包括MongoDB上下文。需要这个是因为如果你的graphql服务器在api路由中,当你构建它时,它不会构建,因为你在api路由中的服务器没有运行。
Mongo文件:plugin/zDb/index:
import {MongoClient} from "mongodb"
export const connectToDatabase = async() => {
const client = new MongoClient(process.env.MONGODB_URI, {useNewUrlParser: true, useUnifiedTopology: true})
let cachedConnection
if(cachedConnection) return cachedConnection
try {
const connection = await client.connect()
cachedConnection = connection
return connection
} catch(error) {
console.error(error)
}
}
export const mongoServer = async() => {
const connect = await connectToDatabase()
return connect.db(process.env.DB_NAME)
}
在 pages 文件夹中,例如 index.js 文件主页:
import {graphql} from 'graphql'
import {schema} from '@/plugin/zSchema/schema'
import {mongoServer} from '@/plugin/zDb/index'
async function query(source, variableValues) {
return graphql({schema, source, contextValue: {mongo: await mongoServer()}, variableValues})
}
export async function getServerSideProps(ctx) {
const listingCurrent = await query(`query($keyField: String, $keyValue: String) {
ListingRQlistingListKeyValue(keyField: $keyField, keyValue: $keyValue) {
address
urlSlug
imageFeature {
photoName
}
}
}`, {
keyField: 'offerStatus'
, keyValue: 'CURRENT'
})
return {props: {
listingCurrent: listingCurrent.data.ListingRQlistingListKeyValue
}
}
}
请注意:graphql调用字段名称来自于:
https://github.com/graphql/graphql-js/blob/fb27b92a5f66466fd8143efc41e1d6b9da97b1f4/src/graphql.js#L62。
export type GraphQLArgs = {|
schema: GraphQLSchema,
source: string | Source,
rootValue?: mixed,
contextValue?: mixed,
variableValues?: ?ObjMap<mixed>,
operationName?: ?string,
fieldResolver?: ?GraphQLFieldResolver<any, any>,
|};
我的模式文件:plugin/zSchema/schema.js
import { makeExecutableSchema } from '@graphql-tools/schema'
import {resolvers} from '@/plugin/zSchema/resolvers'
import {typeDefs} from '@/plugin/zSchema/typeDefs'
export const schema = makeExecutableSchema({resolvers, typeDefs})
@/plugin 文件夹:我在名为 jsconfig.json 的根文件中使用它,将所有文件夹放在 root/plugin 中,并使用 @/plugin 调用它。您可以按照通常的方式导入自己的文件夹结构。
{
"compilerOptions": {
"baseUrl": "."
, "paths": {
"@/*": ["./*"]
}
}
}