1

I am building a graphql api where I have created dummy data for testing and now I was hoping to connect the graphql api to neo4j database using neo4j-graphql library. can some one help me in connecting this graphql api to neo4j database.

schema.js

const {
    GraphQLObjectType,
    GraphQLString,
    GraphQLInt,
    GraphQLSchema,
    GraphQLList,
    GraphQLNonNull
} = require('graphql');

//Hardcode data
const userdata = [
    {id:1, name:'Latha',age:30,weight:40,nationality:'Indian'},
    {id:2, name:'Mahesh',age:20, weight:50,nationality:'mexican'}
]

const userType  =  new GraphQLObjectType({
    name:'User',
    fields:()=>({
        id: {type:GraphQLString},
        name: {type:GraphQLString},
        age: {type:GraphQLInt},
        weight: {type:GraphQLInt},
        nationality: {type:GraphQLString},

    })
});

const RootQuery = new GraphQLObjectType({
    name: 'RootQueryType',
    fields:{
        user:{
            type:userType,
            args:{
                id:{type:GraphQLString}
            },
            resolve(parentValue, args){
                for(let i=0; i<user.length;i++){
                    if(user[i].id == args.id){
                        return user[i];
                    }
                }
            }
        }
    }

});

module.exports = new GraphQLSchema({
    quert: RootQuery
});

server.js

const express = require('express');
const expressGraphQL = require('express-graphql');
const schema = require('./schema.js');

const app = express();

app.use('/graphql', expressGraphQL({
    schema:schema,
    graphiql:true
}));

app.listen(4000, () => {
    console.log('Server is running on port 4000..');
});

1 Answers1

2

The @neo4j/graphql library offers a good getting started documentation, I highly recommend you check it and follow the steps outlined there. It also includes how to set up the server, install the dependencies, etc.

Also, you will not need to specify the GraphQL schema as you have it here, instead, you will have to define GraphQL type definitions and pass them to the server.

In your case the type definitions would look something like this:

const typeDefs = gql`
    type User {
       id: String
       name: String
       age: Int
       weight: Int
       nationality: String
    }
`;

In case you need it, you can even specify custom resolvers. Hope this helps!

Thomas Wiss
  • 144
  • 4
  • Thanks [getting started](https://neo4j.com/docs/graphql-manual/current/getting-started/) documentation it really helped me. can you share me any resources for connecting it to react or serving it as an express api?. Because i want to build a CURD react native application using it – daylightisminetocommand Jul 06 '22 at 12:57
  • 1
    Sure, check [this example application](https://github.com/neo4j/graphql/tree/dev/examples/neo-push), it uses React for the client and has a Node.js express server. It's not React native but it should help in either case. – Thomas Wiss Jul 07 '22 at 07:40