GQL-Prisma с mongodb и nexus записывает в БД, даже если возвращается ошибка - PullRequest
1 голос
/ 15 апреля 2020

В настоящее время мы используем призму (1.34) с mongoDB, nexus (0.11.7) и nexus-prisma (0.3.7).

И у нас возникает следующая проблема:

Когда используется одна из сгенерированных нексусом mutation конечных точек и выдается ошибка при использовании конечной точки - например:

Error: No Node for the model User with value 5e90ed737f8dd933942ee47b for id found.

объект ошибки возвращается клиенту как ожидается:

{
  "errors": [
    {
      "message": "No Node for the model User with value 5e90ed737f8dd933942ee47b for id found.",
      "locations": [
        {
          "line": 2,
          "column": 3
        }
      ],
      "path": [
        "createInformationLog"
      ],
      "extensions": {
        "code": "INTERNAL_SERVER_ERROR",
        "exception": {
          "result": {
            "data": null,
            "errors": [ ...

Но документ, тем не менее, вставлен / обновлен в MongoDB! Кто-нибудь испытывал нечто подобное?

Соответствующие части кода:

const Mutation = prismaObjectType({
  name: 'Mutation',
  definition: t => {
    // expose all mutations generated by prisma
    t.prismaFields(['*'])`
  }

  t.field('signIn', {
     ...
})
import { Application } from 'express'
import { ApolloError } from 'apollo-server'
import { applyMiddleware } from 'graphql-middleware'

import baseSchema from './baseSchema'
import context from './context'
// TODO:
import { Context } from './types'
import permissions from './permissions'
import myHooks from './hooks'

const { ApolloServer } = require('apollo-server-express')
const express = require('express')
const chalk = require('chalk')
const bodyParser = require('body-parser')

const host = ``
const divider = chalk.gray('\n-----------------------------------')

const schema = applyMiddleware(baseSchema, permissions)

//const plugins = [myHooks]
const plugins = []

const server = new ApolloServer({
  schema,
  context,
  plugins
})

const app: Application = express()

app.use('/graphql', bodyParser.text())
app.use('/graphql', (req, _, next) => {
  if (typeof req.body === 'string') {
    req.body = JSON.parse(req.body)
  }
  next()
})

const endpointPath = '/graphql'

server.applyMiddleware({
  app,
  path: endpointPath
  // cors: false
})

app.listen(process.env.PORT || 4000, () => {
  console.log('${chalk.green('Generate Prisma Schema ✓')}')
})

baseSchema.ts

import { makePrismaSchema } from 'nexus-prisma'
import * as path from 'path'

import datamodelInfo from './generated/nexus-prisma'
import { prisma } from './generated/prisma-client'

import { Mutation, Query, User, AuthPayload, EventsCount } from './models'
// provide all the GraphQL types we've implemented
const types = [Mutation, Query, User, AuthPayload, EventsCount]

const baseSchema = makePrismaSchema({
  // provide all the GraphQL types we've implemented
  types,

  // configure the interface to Prisma
  prisma: {
    datamodelInfo,
    client: prisma
  },

  // specify where Nexus should put the generated files
  outputs: {
    schema: path.join(__dirname, './generated/schema.graphql'),
    typegen: path.join(__dirname, './generated/nexus.ts')
  },

  // configure nullability of input arguments: All arguments are non-nullable by default
  nonNullDefaults: {
    input: false,
    output: false
  },

  // configure automatic type resolution for the TS representations of the associated types
  typegenAutoConfig: {
    sources: [
      {
        source: path.join(__dirname, './types.ts'),
        alias: 'types'
      }
    ],
    contextType: 'types.Context'
  }
})

export default baseSchema

docker -compose.yml

services:
  prisma:
    image: prismagraphql/prisma:1.34
    ports:
      - '4466:4466'
    environment:
      PRISMA_CONFIG: |
        port: 4466
        databases:
          default:
            connector: mongo
            uri: mongodb://xxx:xxx@xxxx:27017/admin

...