Understanding GraphQL sometimes hard and confusing. That's why I create this simple project (using minimal framework and using array to represent a database). The goal is simple, to get idea about what is GraphQL and what GraphQL can do.
In this imaginary project let say we have data of artists
and songs
. Songs have relation to artists.
All logic is on index.mjs
file, so it should be simple.
After we understand about GraphQL, I think will be easy later if we want to replace the data layer with real connection to database.
graphql
, as JS reference implementation for GraphQL.graphql-yoga
, as GraphQL server.nodemon
, just a tool that helps develop Node.js based applications by automatically restarting the node application when file changes in the directory are detected.
const dataArtists = [
{ id: 1, name: "Peter Cetera" },
{ id: 2, name: "Dewa 19" },
{ id: 3, name: "Tito Soemarsono" },
{ id: 4, name: "Natalie Imbruglia" },
{ id: 5, name: "David Foster" },
{ id: 6, name: "Kahitna" },
]
const dataSongs = [
{ id: 1, title: "One Clear Voice", artistId: 1 },
{ id: 2, title: "Kangen", artistId: 2 },
{ id: 3, title: "Diam-diam", artistId: 3 },
{ id: 4, title: "Torn", artistId: 4 },
{ id: 5, title: "The Best of Me", artistId: 5 },
{ id: 6, title: "Cantik", artistId: 6 },
{ id: 7, title: "Cerita Cinta", artistId: 6 },
]
songs
, to get all songssong
, to get particular song by idartists
, to get all artistsartist
, to get particular song by id
addSong
, to add new song to arrayupdateSong
, to update particular song by iddeleteSong
, to delete particular song by idaddArtist
, to add new artist to arrayupdateArtist
, to update particular artist by iddeleteArtist
, to delete particular artist by id
- Clone the repository
- Go to the project folder
- Run
npm install
- Run
npm run dev
A web server will run on localhost:5000
.
You can go to http://localhost:5000/graphql
it will show the GraphiQL Yoga screen. You can try query there, let type the sample below.
query {
artists {
id
name
songs {
id
title
}
}
}
It will get list of all artists
data.
MIT
Maintained by Sony Arianto Kurniawan <sony@sony-ak.com> and contributors.