Is it bad to add your postgres connection directly in your graphql resolver?

Is it bad to add your postgres connection directly in your graphql resolver?


0

If I wanted to use the lower level Postgres package from NPM called pg inside my Apollo server so I don’t have to use an ORM. Is it considered bad practice to pass the connection into the resolver directly?

Example:

// ./db/index.ts

import { Pool } from 'pg'

const pool = new Pool({
  user: 'your_username',
  host: 'your_host',
  database: 'your_database',
  password: 'your_password',
  port: 5432,
});

export default pool
// ./index.ts

import { ApolloServer, gql } from 'apollo-server'
import pool from './db'

const typeDefs = gql`
  type Query {
    getUsers: [User]
  }

  type User {
    id: ID
    name: String
    email: String
  }
`;

const resolvers = {
  Query: {
    getUsers: async () => {
      const result = await pool.query('SELECT * FROM users');
      return result.rows;
    },
  },
};

const server = new ApolloServer({ typeDefs, resolvers });

server.listen().then(({ url }) => {
  console.log(`Server running at ${url}`);
});


Load 4 more related questions


Show fewer related questions

0



Leave a Reply

Your email address will not be published. Required fields are marked *