Custom GraphQL resolvers

Hi, how do i access neo4j database from my GraphQL resolver(ctx).

I'm trying to search the database for the existence of email before running CreateUser Mutation, on condition that the email doesn't already exist

1 Like

Have answer??? i need the same ...

Okay so in your index.js file, where you build your augmented schema bring in the exports of a resolvers.js file:

index.js:

import resolvers from './resolvers';

const schema = makeAugmentedSchema( {
  typeDefs,
  config: {
    auth: {
      hasRole: true,
      isAuthenticated: true,
      hasScope: false,
    },
  },
  resolvers, //<----------
} );

then in your resolvers.js create a mutation function which reflects the mutation listed schema.graphql file

resolvers.js:

Mutation: {
    /* NEW USER */
    CreateMember: async ( obj, params, ctx, resolveInfo ) => {
      params.a = await bcryptjs.hash( params.a, 10 );
      const findUser = await ctx.driver
        .session()
        .run( `MATCH (u:User {email: "${params.email}"}) return u` );
      if ( findUser.records.length > 0 ) {
        throw new ApolloError( 'This user already exists', 200, [
          'user_already_exists',
        ] );
      }
      return neo4jgraphql( obj, params, ctx, resolveInfo, true );
    },

when you run this function it will pass the user data back and eventually perform the actions you give cypher in the schema file, so at the bottom of the schema.graphql:

type Mutation {
  CreateMember(email: String!, a: String!, name: String!): User
    @cypher(
      statement: """
      MERGE (u:User {email: $email})
      ON CREATE SET
        u.id = apoc.create.uuid(),
        u.email = $email,
        u.name = $name,
        u.created = datetime(),
        u.softDeleted = false
      ON MATCH SET
        u.a = $a,
        u.updated = datetime()
      MERGE (r:Role {name: 'Member'})
      CREATE (u)-[p:PLAYS]->(r)
      RETURN u
      """
    )