javascriptnode.jsneo4jgraphqlneo4j-graphql-js

how to add neo4j-graphql library to graphql api


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..');
});

Solution

  • 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!