#Apollo: "Cannot read properties of undefined (reading 'find')". Not getting Entity Manager context

3 messages · Page 1 of 1 (latest)

summer pike
#

!screenshot

random girderBOT
#
`!screenshot`:

Rather than screenshots, please provide either code formatted as:

```ts
// code here
```
Or even better, as an example on the TypeScript playground that is as simple as possible and reproduces the issue. This makes it easier to help you and increases the chances of getting an answer.

mossy tulip
# summer pike !screenshot

sorry, heres according to the guidelines

heres my PostResolver.ts

import 'reflect-metadata'
import { Post } from '../entities/Post';
import { MikroORMApolloContext } from 'src/interfaces/context.interface';
import { Resolver, Query, Mutation, Ctx, Arg } from 'type-graphql';

// FIX: Not actually recieving the Entity Manager as context, so 'find'
// or any CRUD operation doesn't error, which is weird since the LSP catches
// the EM's methods.

@Resolver(Post)
export class PostResolver {
  @Query(() => [Post])
  async getPosts(
    @Ctx() ctx: MikroORMApolloContext
  ): Promise<Post[]> {
    console.log('ctx', ctx); // outputs: {}
    console.log('ctx.em:', ctx.em); // outputs: undefined

    return ctx.em.find(Post, {});
  }

heres my context.interface.ts

import { Connection, EntityManager, IDatabaseDriver } from '@mikro-orm/core';
import { Request, Response } from 'express';

export type MikroORMApolloContext = {
  req: Request;
  res: Response;
  em: EntityManager<IDatabaseDriver<Connection>>;
}

heres my index.ts's main function where im currently initializing the apollo server and the mikro-orm instance

const main = async () => {
  const PORT = process.env.PORT;

  const orm = await MikroORM.init<PostgreSqlDriver>(config);
  await orm.getMigrator().up();

  const apolloServer = new ApolloServer({
    schema: await buildSchema({
      resolvers: [PostResolver]
    })
  });

  const { url } = await startStandaloneServer(apolloServer, {
    context: async () => ({ em: orm.em.fork() }),
    listen: { port: 4000 }
  });

  const app = express();

  console.log('Apollo server running ' + url);

  app.listen(PORT, () => {
    console.log(`Express server running at port: ${PORT}`);
  });

  app.use('/graphql', json(), expressMiddleware(apolloServer));

};