mercurius-js / mercurius

Implement GraphQL servers and gateways with Fastify
https://mercurius.dev/
MIT License
2.35k stars 237 forks source link

Docs: Database Integration #352

Open PeteSolid opened 3 years ago

PeteSolid commented 3 years ago

Hi, I am a beginner and it is not quite clear to me how to combine it with a Database like PostgresQL to read and write? Are there docs for that? Many thanks!

mcollina commented 3 years ago

Unfortunately there are not! It would be great to create such content - I'll leave this open as a Good First Issue.

voxpelli commented 3 years ago

I can leave a small description here right away, in a few steps:

  1. Add something like fastify-postgres:
    
    const fastifyPostgres = require('fastify-postgres').default;

app.register(fastifyPostgres, { connectionString: process.env.DATABASE_URL });


2. Add `mercurius` and a schema:

```javascript
const schema = `
  schema {
    query: Query
  }

  type Query {
    foo(id: ID!): String
  }
`;

const mercurius = require('mercurius').default;

app.register(mercurius, {
  schema,
  resolvers: {
    Query: {
      foo: fooResolver
    }
  }
});
  1. And then to complete it: In your GraphQL resolver, you will (unless you have changed the default) find the Fastify app instance as app on the GraphQL context. And on the Fastify app instance you can then access fastify-postgres as app.pg and thus complete the above setup by eg. doing a app.pg.query():
const fooResolver = async (parent, args, context, info) => {
  const { app } = context;
  const { id } = args;

  const result = await app.pg.query('SELECT bar FROM foo WHERE foo.id = $1', [id]);

  return result.rows[0] && result.rows[0].bar;
};

Would you be interested in me wrapping that up as a PR @mcollina?

ruheni commented 3 years ago

Hi @PeteSolid 👋🏾

I created a PR, giving an example of how you can work with databases in Mercurius using Prisma. You can work with other ORMs too other than Prisma too. 🙂

In case you hit any snag, feel free to reach out! 😉