0

I am following a Ben Awad tutorial, and in this project, I am using Typescript, Mikro-Orm and GraphQL and am very much new to all this stuff.

I am getting the following error trace on GraphQL:

{
  "errors": [
    {
      "message": "Using global EntityManager instance methods for context specific actions is disallowed. If you need to work with the global instance's identity map, use `allowGlobalContext` configuration option or `fork()` instead.",
      "locations": [
        {
          "line": 2,
          "column": 3
        }
      ],
      "path": [
        "posts"
      ],
      "extensions": {
        "code": "INTERNAL_SERVER_ERROR",
        "exception": {
          "name": "ValidationError",
          "stacktrace": [
            "ValidationError: Using global EntityManager instance methods for context specific actions is disallowed. If you need to work with the global instance's identity map, use `allowGlobalContext` configuration option or `fork()` instead.",
            "    at Function.cannotUseGlobalContext (C:\\Users\\kvnka\\OneDrive - Trinity College Dublin\\GitHub\\kBlog\\node_modules\\@mikro-orm\\core\\errors.js:83:16)",
            "    at SqlEntityManager.getContext (C:\\Users\\kvnka\\OneDrive - Trinity College Dublin\\GitHub\\kBlog\\node_modules\\@mikro-orm\\core\\EntityManager.js:1030:44)",
            "    at SqlEntityManager.find (C:\\Users\\kvnka\\OneDrive - Trinity College Dublin\\GitHub\\kBlog\\node_modules\\@mikro-orm\\core\\EntityManager.js:93:25)",
            "    at PostResolver.posts (C:\\Users\\kvnka\\OneDrive - Trinity College Dublin\\GitHub\\kBlog\\dist\\resolvers\\post.js:20:19)",
            "    at C:\\Users\\kvnka\\OneDrive - Trinity College Dublin\\GitHub\\kBlog\\node_modules\\type-graphql\\dist\\resolvers\\create.js:34:68",
            "    at Object.applyMiddlewares (C:\\Users\\kvnka\\OneDrive - Trinity College Dublin\\GitHub\\kBlog\\node_modules\\type-graphql\\dist\\resolvers\\helpers.js:58:16)",
            "    at C:\\Users\\kvnka\\OneDrive - Trinity College Dublin\\GitHub\\kBlog\\node_modules\\type-graphql\\dist\\resolvers\\create.js:27:26",
            "    at field.resolve (C:\\Users\\kvnka\\OneDrive - Trinity College Dublin\\GitHub\\kBlog\\node_modules\\apollo-server-core\\dist\\utils\\schemaInstrumentation.js:56:26)",
            "    at resolveFieldValueOrError (C:\\Users\\kvnka\\OneDrive - Trinity College Dublin\\GitHub\\kBlog\\node_modules\\graphql\\execution\\execute.js:502:18)",
            "    at resolveField (C:\\Users\\kvnka\\OneDrive - Trinity College Dublin\\GitHub\\kBlog\\node_modules\\graphql\\execution\\execute.js:460:16)"
          ]
        }
      }
    }
  ],
  "data": null
}

When I query this:

{
  posts {
    id
    createdAt
    updatedAt
    title
  }
}

This is my index.ts file:

const main = async () => {
    const orm = await MikroORM.init(microConfig);
    await orm.getMigrator().up();

    const app = express();
    await RequestContext.createAsync(orm.em, async () => {
        
    })
    const apolloServer = new ApolloServer({
        schema: await buildSchema({
            resolvers: [HelloResolver, PostResolver],
            validate: false
        }),
        context: () => ({em: orm.em})
    });
    
    await apolloServer.start();
    apolloServer.applyMiddleware({app});

    app.listen(5000, () => {
        console.log("server started on port 5000");
    });
}

This is my post.ts resolver file:

@Resolver()
export class PostResolver{
    @Query(()=> [Post])
    posts(@Ctx() {em}: MyContext): Promise<Post[]>{
        return em.find(Post, {});
    }
}

And finally my entity Post.ts file (to give context regarding my GraphQL query above):

@ObjectType()
@Entity()
export class Post{
    @Field(() => Int)
    @PrimaryKey()
    id! : number;

    @Field(() => String)
    @Property({type: 'date'})
    createdAt = new Date();

    @Field(()=> String)
    @Property({type: 'date',onUpdate: () => new DataTransfer()})
    updatedAt = new Date();

    @Field()
    @Property({type: 'text'})
    title! : string;
}

I tried following the answers under this thread which was a very similar issue.

My code is a bit different to the OP of that thread, so I'm not sure how to implement the RequestContext into my code. I want to try to avoid simply disabling the validation, as I will have servers and middlewares down the line.

I hope someone can point me towards the right direction.

1 Answers1

-1

Open your mikro-orm.config.ts file in src add allowGlobalContext: true in your config variable in the mikro-orm.config file

import { Post } from "../entities/Post";
import { __prod__ } from "./constants";
import  { Options } from "@mikro-orm/core";
import path from "path";    

const config: Options = {
    allowGlobalContext: true,
    migrations:{
        path: path.join(__dirname,'./migrations'),
        pathTs: undefined, 
        glob: '!(*.d).{js,ts}'
    },
        entities: [Post],
        dbName: 'lireddit',
        user: 'postgres',
        password: 'root',
        type: 'postgresql',
        debug: !__prod__,
    
};
export default config;

The error says that you have to allowGlobalContext, at the time of ben awad tuturiol the graphql doesn't have a sandbox update, it has now. So we have to set allowGlobalContext to be true.

SwissCodeMen
  • 4,222
  • 8
  • 24
  • 34