How can I make this as optimisticResponse? - graphql

I have a "like" button/mutation. There is still a split second while I get a response from the server. How can I make this as an optimisticResponse?
Here's my mutation:
const LIKE_MUTATION = gql`
mutation LIKE_MUTATION($postId: ID!) {
createLike(postId: $postId) {
id
post {
id
title
text
createdAt
author {
id
}
likes {
id
user {
id
}
}
}
}
}
`
Now what I'm trying to do in my Mutation component is:
optimisticResponse={{
__typename: 'Mutation',
createLike: {
__typename: 'Like',
id: this.props.post.id,
post: this.props.post,
likes: this.props.post.likes.concat({
id: 'vcjsvdcjscd',
user: { name: 'sample', id: 'jsdckbsdjcbdjs' },
}),
},
}}
the like is connected to post and to user in my schema. I'm trying to provide fake user id and name here. It doesn't work. I get this in the console as well:
Missing field id in {
"name": "user",
"__typename": "User"
}

Related

Graphql insert a child while indicating his parent

I'm very new into graphql but I'm able to insert a new "notification" that belongs to a "Tienda" which means store, however I'm not able to indicate to which store it belongs to.
This is the schema
type Tienda #model {
id: ID!
name: String!
cliente: [Cliente] #manyToMany(relationName: "clienteDeTienda")
news: [Notificacion] #hasMany
}
type Cliente #model {
id: ID!
name: String!
stores: [Tienda] #manyToMany(relationName: "clienteDeTienda")
}
type Notificacion #model {
id: ID!
store: Tienda #belongsTo
content: String!
}
This is how I insert a new notification:
const response = await API.graphql(graphqlOperation(createNotificacion, {input:data}))
This is what data has inside:
Object {
"content": "Nueva notificacion",
}
And this is the response I get from console.log(response):
Object {
"data": Object {
"createNotificacion": Object {
"content": "Nueva notificacion",
"createdAt": "2022-11-13T18:04:55.000Z",
"id": "9f50d333-fc9e-478f-be6a-c54275797a27",
"store": null,
"tiendaNewsId": null,
"updatedAt": "2022-11-13T18:04:55.000Z",
},
},
}
As you can see "content" was added to the notification but "store" is null but I haven't been successful in inserting the store ID in there.
This is how the mutations is defined:
export const createNotificacion = /* GraphQL */ `
mutation CreateNotificacion(
$input: CreateNotificacionInput!
$condition: ModelNotificacionConditionInput
) {
createNotificacion(input: $input, condition: $condition) {
id
store {
id
name
cliente {
nextToken
}
news {
nextToken
}
createdAt
updatedAt
}
content
createdAt
updatedAt
tiendaNewsId
}
}
`;
I've tried with the following 3 methods which give no error but still doesn't link to it's parent:
API.graphql(graphqlOperation(createNotificacion, {input:data, store:{id:'55988776-11af-42b8-b93b-9de9af35f7dc'}}))
And
API.graphql(graphqlOperation(createNotificacion, {input:data, store:'55988776-11af-42b8-b93b-9de9af35f7dc'}))
And:
API.graphql(graphqlOperation(createNotificacion, {input:data},{store:'55988776-11af-42b8-b93b-9de9af35f7dc'}))
Please somebody point me the right path or documentation about how to do this. I need to know how to perform the graphqlOperation correctly.
Thank you very much
In the end what I had to do is this:
const response = await API.graphql(graphqlOperation(createNotification, {input:{...data, storeNotificationsId:'someValidStoreId'}}));

Unable to fetch component data using Graphql in Strapi

I am building Graphql api with Strapi. It's a simple application which user can signup and save some of his/her information. I have two tables for that, User [Which is Strapi provided] and Profile which i use to store user additional information. The two tables has relationship
User [User has and belongs to one Profile]
Profile Profile has and belongs to one User and contact component structure.
I want to be able to fetch the current logged in user and it's information from Profile table, but the Contact field which i save as component type return null.
Here is what i am doing so far
extensions/user-permission/config/schema.graphql.js
module.exports = {
definition: `
extend type UsersPermissionsMe {
profile: ProfileMe
}
type ProfileMe {
id: ID!
website: String!
description: String!
contact: ContactMe
}
type ContactMe {
id: ID!
name: String!
phone: String!
email: String!
}
`
}
extensions/user-permission/services/User.js
'use strict';
module.exports = {
fetchAuthenticatedUser(id) {
return strapi.query('user', 'users-permissions').findOne({ id }, ['role', 'profile']);
},
};
And when run GraphQl Query
query {
me {
username
email
profile {
website
description
contact {
name
phone
email
}
}
}
}
it returned
{
"data": {
"me": {
"username": "company",
"email": "company#test.com",
"profile": {
"website": "http://localhost.com",
"description": "lorem text",
"contact": null
}
}
}
}
I want to also get contact data here. I hope someone on Internet can help me.
please help, thanks you.

Create GraphQL connection between User and Role Type via Role and query them

I want to create a GraphQL connection between User <> Role <> Role_Type and finally get the User Role Type back with a query. Here is brake it down to the only important lines of code:
type Query {
getUsers: [User]
}
type User {
_id: ID
firstname: String
roles: [Role]
}
type Role {
_id: ID
role_type_id: ID
role_types: [Role_Type]
user_id: ID
}
type Role_Type {
_id: ID
name: String
}
and in the User resolver I have:
Query: {
getUser: async (root, { _id }) => {
return prepare(await DBUsers.findOne(ObjectId(_id)))
}
},
User: {
roles: async ({_id}) => {
return (await MongoDBRoles.find({user_id: _id}).toArray()).map(prepare)
}
}
and for the Role resolver:
Role: {
role_types: async ({_id}) => {
return (await MongoDBRoleTypes.find({role_type_id: _id}).toArray()).map(prepare)
},
},
When I query now with:
{
getUser(_id: "5d555adcd2c22a242863f7a1") {
firstname
roles {
_id
role_type_id
user_id
role_types {
name
}
}
}
}
I get:
{
"data": {
"getUser": {
"firstname": "Gregor",
"roles": [
{
"_id": "5d90cf352f50882ab0ce3877",
"role_type_id": "5d90ce48b7893d19bcc328f9",
"user_id": "5d555adcd2c22a242863f7a1",
"role_types": []
}
]
}
}
}
But why is role_types empty. As you can see the role_type_id is filled. So why there is no connection.
When I watch into MongoDB I can see the Role Type of the user.
If you need more Schema/Resolver let me know.
Ok it was kind of easy to fix. Actually the Role resolver was going multiple matches. But somehow it needs to be single lookup. That does not make much sense but somehow the search for the id lookup is a single lookup. Anyway here is what I have changed and now it works properly.
Replace this:
role_types: async ({_id}) => {
return (await MongoDBRoleTypes.find({role_type_id: _id}).toArray()).map(prepare)
},
with:
role_type: async ({role_type_id}) => {
return prepare(await DBRoleTypes.findOne(ObjectId(role_type_id)))
},
and you fix this.

Linking schema in Apollor server 2

I have a case that I'm not sure to implement, I have a REST API that returns an array of user IDs. Like this:
{
status: ""
"users": [
{
"userId": ID
},
{
"userId": ID
}
]
}
I want to have the ability to get the user details for each userID, so I want to pass the ID to another API that gets the user details.
The issue is that the second API returns the information as follows
{
status: ""
data:[{
Info:{
userId:
name:
...
}
Permissions{
...
}
...
}]
}
My issue is how can I represent this relation in the schema?
This is the schema I came up with:
Query{
EventUsersSummary(eventId: ID): EventResponse!
}
type EventResponse{
status: String!
users: [EventUser!]!
}
type EventUser {
userId: ID!
}
type User {
info: Info
permissions: Permissions
....
}
type Info{
userId: ID
firstName: String
lastName: String
email: Email
}
....
In the resolver for EventResponse I'm removing status from the result. In the resolver I plan to return the information for each user.

Any reason I am getting back the query name in the GraphQL results?

Using the makeExecutableSchema with the following Query definition:
# Interface for simple presence in front-end.
type AccountType {
email: Email!
firstName: String!
lastName: String!
}
# The Root Query
type Query {
# Get's the account per ID or with an authToken.
getAccount(
email: Email
) : AccountType!
}
schema {
query: Query
}
And the following resolver:
export default {
Query: {
async getAccount(_, {email}, { authToken }) {
/**
* Authentication
*/
//const user = security.requireAuth(authToken)
/**
* Resolution
*/
const account = await accounts.find({email})
if (account.length !== 1) {
throw new GraphQLError('No account was found with the given email.', GraphQLError.codes.GRAPHQL_NOT_FOUND)
}
return account
}
}
}
When I query with:
query {
getAccount(email: "test#testing.com") {
firstName
lastName
}
}
I am getting the following result in GraphiQL:
{
"data": {
"getAccount": {
"firstName": "John",
"lastName": "Doe"
}
}
}
So, any reason I am getting this "getAccount" back in the result?
Because getAccount is not a query name. It's just a regular field on the root query type Query.
And having results on the exact same shape as the query is one of the core design principles of GraphQL:
Screenshot from http://graphql.org/ site
Query name in GraphQL goes after query keyword:
query myQueryName {
getAccount(email: "test#testing.com") {
firstName
lastName
}
}

Resources