This is the first time I am using graphQL, I have two questions related to it.
I have vaguely gone through the docs and was building something of my own.
So, My setup right now is very simple. In the starting point of my app, I have something like this
const express = require('express')
const app = express();
const graphqlHTTP = require("express-graphql")
const schema = require('./schema/schema')
app.use("/graphql", graphqlHTTP({
schema: schema
}));
app.get('/', (req, res) => {
res.json({"message": "Welcome to EasyNotes application. Take notes quickly. Organize and keep track of all your notes."});
});
//Listen to specific post
app.listen(4000, () => {
console.log("Listening for request on port 4000")
});
And my Schema looks like this
const graphql = require("graphql")
const {
GraphQLObjectType,
GraphQLString,
GraphQLSchema,
GraphQLList,
GraphQLID,
GraphQLNonNull,
GraphQLInt
} = graphql
const GenderType = new GraphQLObjectType({
name: 'Gender',
fields: () => ({
male: {
}
})
})
const UserType = new GraphQLObjectType({
name: 'User', // Importance of Name here
fields: () => ({
id: {
type: GraphQLID
},
name: {
type: GraphQLString
},
gender: {
type: GenderType // Create custom type for it later
}
})
})
In my above code snippet, Inside UserType
I want my GenderType
to be either male or female. How would write my custom type such that it only accepts value 'male' or 'female'?
What you want to do can be achieved with both Scalar Types and Enum Types. In your case you probably want to go with an enum because you have a small finite list of allowed values. Using the Enum Type will show the allowed values in the documentation in GraphiQL. In most GraphQL APIs Enum values use all capital values but you could use the
value
property to transparently map thefemale
value toFEMALE
. This would for example allow you to treat the values as lower case on the server side (we do this a lot because the values come in lower case from our postgres). Here some code for inspiration: