example of basic auth for graphql queries
this just an example of how we can user GraphQL with user authentication to create new posts / to show user posts
To pass the session
to the root argument for the solvers, we pass object with the session variable to rootValue
:
.use('/graphql', bodyParser.json(), graphqlHTTP(req => ({
// some code here..
rootValue: { session: req.session },
})))
npm i
npm start
and then open http://localhost:3000/graphql in your browser
mutation {
createUser(login:"SomeUser", pw:"myPass") {
_id
login
pw
}
}
Result:
{
"data": {
"createUser": {
"_id": "5d036f8fe9ad5b24efab7eaf",
"login": "SomeUser",
"pw": "myPass"
}
}
}
loginUser(login:"SomeUser", pw:"myPass") {
_id
login
pw
}
}
Result:
{
"data": {
"loginUser": {
"_id": "5d036f8fe9ad5b24efab7eaf",
"login": "SomeUser",
"pw": "myPass"
}
}
}
mutation {
createPost(title:"First post", content:"this is my first post, just for test!") {
_id
title
content
}
}
Result:
{
"data": {
"createPost": {
"_id": "5d0378e9e9ad5b24efab7eb0",
"title": "First post",
"content": "this is my first post, just for test!"
}
}
}
query {
post(_id:"5d0378e9e9ad5b24efab7eb0") {
_id
userId
title
content
comments {
_id
postId
content
}
}
}
Result:
{
"data": {
"post": {
"_id": "5d0378e9e9ad5b24efab7eb0",
"userId": "5d036f8fe9ad5b24efab7eaf",
"title": "First post",
"content": "this is my first post, just for test!",
"comments": []
}
}
}
As you can see the userID field was set to your user._id
mutation {
createComment(postId:"5d0378e9e9ad5b24efab7eb0", content:"this is my first comment!") {
_id
postId
content
}
}
{
"data": {
"createComment": {
"_id": "5d0383640172c0552fbd515e",
"postId": "5d0378e9e9ad5b24efab7eb0",
"content": "this is my first comment!"
}
}
}
{
"data": {
"posts": [
{
"_id": "5d0378e9e9ad5b24efab7eb0",
"userId": "5d036f8fe9ad5b24efab7eaf",
"title": "First post",
"content": "this is my first post, just for test!",
"comments": [
{
"_id": "5d0383640172c0552fbd515e",
"postId": "5d0378e9e9ad5b24efab7eb0",
"content": "this is my first comment!"
}
]
}
]
}
}
mutation {
logoutUser(_id:"5d036f8fe9ad5b24efab7eaf")
}
Result:
{
"data": {
"logoutUser": true
}
}
query {
posts {
_id
userId
title
content
}
}
Result:
{
"data": {
"posts": null
}
}