Software Engineering :: API :: Architectural Style :: GraphQL :: Training :: Learning GraphQL :: 4. Creating a GraphQL Server Schema
⪼ Made with 💜 by Polyglot.
A language which defines all of our APIs types
-
Int -
Float -
String -
Boolean -
ID
id: ID!
name: String!
Container of
Scalarand otherObjectTypes
type Photo {
id: ID!
name: String!
url: String!
description: String
rating: Float
private: Boolean!
}
!: value must be non-null
name: String!
description: String
type Query {
totalUsers: Int!
}
type User {
postedPhotos: [Photo!]!
}
photos: [Photo]: Nullable list of nullable valuesphotos: [Photo]!: Non-nullable list of nullable valuesphotos: [Photo!]!: Non-nullable list of non-nullable values (empty array is valid)
» npm init -y
» npm install graphql apollo-server nodemon
» code .
const { ApolloServer, gql } = require('apollo-server');
const typeDefs = gql`
type Query {
totalDays: Int!
}
`;
// const resolvers = {};
const server = new ApolloServer({
typeDefs,
mocks: true,
});
server
.listen()
.then(({ url }) =>
console.log(`Server running at ${url}`)
);
{
"name": "ski-day-counter",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"start": "nodemon ."
},
"keywords": [],
"author": "",
"license": "ISC",
"dependencies": {
"apollo-server": "^2.25.0",
"graphql": "^15.5.0",
"nodemon": "^2.0.7"
}
}
» npm start
Define an Object Type
const { ApolloServer, gql } = require('apollo-server');
const typeDefs = gql`
type SkiDay {
id: ID!
date: String!
mountain: String!
}
type Query {
totalDays: Int!
allDays: [SkiDay!]!
}
`;
// const resolvers = {};
const server = new ApolloServer({
typeDefs,
mocks: true,
});
server
.listen()
.then(({ url }) =>
console.log(`Server running at ${url}`)
);
query {
totalDays
allDays {
id
date
mountain
}
}
Adding an enumeration type
const { ApolloServer, gql } = require('apollo-server');
const typeDefs = gql`
type SkiDay {
id: ID!
date: String!
mountain: String!
conditions: Conditions
}
enum Conditions {
POWDER
HEAVY
ICE
THIN
}
type Query {
totalDays: Int!
allDays: [SkiDay!]!
}
`;
// const resolvers = {};
const server = new ApolloServer({
typeDefs,
mocks: true,
});
server
.listen()
.then(({ url }) =>
console.log(`Server running at ${url}`)
);
query {
totalDays
allDays {
id
date
mountain
conditions
}
}




