Apollo Server Express + GraphQL relationships - node.js

I am using Express + Apollo Server + GraphQL + Mongoose + MongoDB to "perform" several CRUD operations on a database.
One of the operations I am trying to make is to get the sites from the database and expand its users with their information for each record like this:
query {
getSites {
id
name
owner {
name
email
}
origins
}
}
Instead, I am getting these results:
{
"data": {
"getSites": [{
"id": "5cae36182ab9b94e94ba9af5",
"name": "Test site 1",
"owner": [{
"name": null,
"email": null
}
],
"origins": [
"test1",
"test2"
]
}, {
"id": "5cae3a3798c302247c036544",
"name": "Test site 2",
"owner": [{
"name": null,
"email": null
}
],
"origins": [
"test1",
"test2"
]
}
]
}
}
This is my typeDef code for Site:
import { gql } from 'apollo-server-express';
const site = gql `
extend type Site {
id: ID!
name: String!
origins: [String]
owner: [User]
createdOn: String
updatedOn: String
}
extend type Query {
getSites: [Site]
getSite(id: ID!): Site
}
extend type Mutation {
addSite(name: String!, owner: [String!], origins: [String]): Site
}
`;
export default site;
If I console.log(sites) I see owner is an array of Strings.
Edit:
If I change addSite(name: String!, owner: [User], origins: [String]): Site then I get when compiling:
Error: The type of Mutation.addSite(owner:) must be Input Type but got: [User]
My resolver looks like this:
getSites: async () => await Site.find().exec()
What's the proper way to define relationships today? Thanks.

I just edited my resolver to this:
getSites: async () => {
let sites = await Site.find().exec();
let ownedSites = await User.populate(sites, { path: 'owner' });
return ownedSites;
}
And that solved the errors.

Related

Order result resolved via resolver in graphql + apollo server + nodejs

I am trying to order an array returned by resolver in GraphQL.
I can only think of way of ordering data using DB Query, but how can we order data that GraphQL resolves using its resolver functions?
Below is my Query resolver:
getAllNotifications: (
_parent,
_args: { authorId: string },
context: Context
) => {
return context.prisma.blog.findMany({
where: {
authorId: _args.authorId,
},
orderBy: {
created_at: "desc",
},
});
},
And my query:
query Query($authorId: String) {
getAllNotifications(authorId: $authorId) {
title
comment {
id
created_at
}
}
}
And result:
{
"data": {
"getAllNotifications": [
{
"title": "First Ride! ",
"comment": [ <--- I am trying to order this comment array using created_at date
{
"id": "cl8afqaqx001209jtxx7mt5h6",
"created_at": "2022-09-20T16:53:07.689Z"
},
{
"id": "cl8agiq71001509l27or7oxyd",
"created_at": "2022-09-20T17:15:14.077Z"
},
{
"id": "cl8ahmvrm003109l8dp684bn6",
"created_at": "2022-09-20T17:46:27.538Z"
},
{
"id": "cl99kj24p002609iajdbpycg0",
"created_at": "2022-10-15T06:59:24.169Z"
}
]
}
]
}
}
I didn't found anything in Graphql docs regarding ordering data returned by resolver
GraphQL doesn't have functions for selection and ordering, those are jobs that resolvers must do.
Add a resolver for comment that sorts the comment array. Your existing sort just sorts based on the created_at date of the post.

How to use Convector to querie CouchDB Rich Queries with JSON Objects?

I'm here with a problem with rich queries and convector chaincodes, everything works with mango queries, but when I pass content object it's is stringifyed and don't will be sent has an object, but is converted to a string "content":"{\"data\":\"1971\"}", obvious it fails the query
original sample query
{
"selector": {
"type": "io.worldsibu.examples.person",
"attributes": {
"$elemMatch": {
"id": "born-year",
"content": {
"data": "1971"
}
}
}
}
}
graphql query variables
{
"getByAttributeInput": {
"id": "born-year",
"content": {
"data": "1971"
}
},
"skip": 0,
"take": 10
}
packages/person-cc/src/person.controller.ts
chaincode controller method
#Invokable()
public async getByAttribute(
#Param(yup.string())
id: string,
#Param(yup.mixed())
value: any
) {
return await Person.query(Person, {
selector: {
type: c.CONVECTOR_MODEL_PATH_PERSON,
attributes: {
$elemMatch: {
id: id,
content: value
}
}
}
});
}
in docker logs we can view that value is content is sent has a string and not a object ex "content":"{\"data\":\"1971\"}"
{"selector":{"type":"io.worldsibu.examples.person","attributes":{"$elemMatch":{"id":"born-year","content":"{\"data\":\"1971\"}"}}}}
the trick is change #Param(yup.mixed()) to #Param(yup.object()) and now it works has expected, we can query attributes content value with arbitrary and complex objects
#Invokable()
public async getByAttribute(
#Param(yup.string())
id: string,
// #Param(yup.mixed())
#Param(yup.object())
value: any
) {
...

customize json response in graphQL

i use Express-js and express graphQL module to create my endpoint and web service ;
i am looking for way to create custom response in graphQL my endpoint is simple
select books from database my response is
{
"data": {
"books": [
{
"id": "5b5c02beab8dc1182b2e0a03",
"name": "dasta"
},
{
"id": "5b5c02c0ab8dc1182b2e0a04",
"name": "dasta"
}
]
}
}
but in need something like this
{
"result": "success",
"msg" : "list ...",
"data": [
{
"id": "5b5c02beab8dc1182b2e0a03",
"name": "dasta"
},
{
"id": "5b5c02c0ab8dc1182b2e0a04",
"name": "dasta"
}
]
}
here is my bookType
const BookType = new GraphQLObjectType({
name: 'Book',
fields: () => ({
id: {type: GraphQLID},
name: {type: GraphQLString},
genre: {type: GraphQLString},
author_id: {type: GraphQLString},
author: {
type: AuthorType,
resolve(parent, args) {
return Author.findById(parent.author_id);
}
}
})
});
That's not a legal GraphQL response. As per section 7.1 of the spec, after describing the data, errors, and extensions: top-level keys:
... the top level response map must not contain any entries other than the three described above.
You might put this data into extensions; or make it an explicit part of your GraphQL API; or simply let "success" be implied by the presence of a result and the lack of an error.

GraphQL - show list or single object

I have managed to get following data through GraphQL:
{
"data": {
"city": {
"name": "Eldorado",
"users": [
{
"username": "lgraham1"
},
{
"username": "ehowell"
},
{
"username": "cbauch"
}
]
}
}
}
I have QueryType, CityType and UserType. In my QueryType I fetch city and display users by GraphQLList(UserType). What should I do if I want to display single user if there is an id provided?
My API looks like this:
all cities:
/cities/
single city:
/cities/:city_id
users for particular city:
/cities/:city_id/users
single user:
/cities/:city_id/users/:user_id
You'll need to add a user query to your main Query object.
Assuming your id is an Integer, you would do this
const Query = new GraphQLObjectType({
name: 'RootQuery',
fields: {
// ...
user: {
type: User,
args: {
id: {
type: new GraphQLNonNull(GraphQLInt)
}
},
resolve: function(rootValue, args) {
return db.users.findOne(args)
}
}
}
})
const Schema = new GraphQLSchema({
query: Query,
// ...
});
Then you can query using
{
user (id: 12345) {
...
}
}
Or you could make a function
query findUser ($id: Int!) {
user (id: $id) {
...
}
}

Unable to fetch list in react relay

I am following schema same as mentioned here
I want to fetch all users so I updated my schema like this
var Root = new GraphQLObjectType({
name: 'Root',
fields: () => ({
user: {
type: userType,
resolve: (rootValue, _) => {
return getUser(rootValue)
}
},
post: {
type: postType,
args: {
...connectionArgs,
postID: {type: GraphQLString}
},
resolve: (rootValue, args) => {
return getPost(args.postID).then(function(data){
return data[0];
}).then(null,function(err){
return err;
});
}
},
users:{
type: new GraphQLList(userType),
resolve: (root) =>getUsers(),
},
})
});
And in database.js
export function getUsers(params) {
console.log("getUsers",params)
return new Promise((resolve, reject) => {
User.find({}).exec({}, function(err, users) {
if (err) {
resolve({})
} else {
resolve(users)
}
});
})
}
I am getting results in /graphql as
{
users {
id,
fullName
}
}
and results as
{
"data": {
"users": [
{
"id": "VXNlcjo1Nzk4NWQxNmIwYWYxYWY2MTc3MGJlNTA=",
"fullName": "Akshay"
},
{
"id": "VXNlcjo1Nzk4YTRkNTBjMWJlZTg1MzFmN2IzMzI=",
"fullName": "jitendra"
},
{
"id": "VXNlcjo1NzliNjcyMmRlNjRlZTI2MTFkMWEyMTk=",
"fullName": "akshay1"
},
{
"id": "VXNlcjo1NzliNjgwMDc4YTYwMTZjMTM0ZmMxZWM=",
"fullName": "Akshay2"
},
{
"id": "VXNlcjo1NzlmMTNkYjMzNTNkODQ0MmJjOWQzZDU=",
"fullName": "test"
}
]
}
}
but If I try to fetch this in view as
export default Relay.createContainer(UserList, {
fragments: {
userslist: () => Relay.QL`
fragment on User #relay(plural: true) {
fullName,
local{
email
},
images{
full
},
currentPostCount,
isPremium,
}
`,
},
});
I am getting error Minified exception occurred; use the non-minified dev environment for the full error message and additional helpful warnings.
Please tell me what I am missing .
I tried a lot with and without #relay(plural: true).
Also tried to update schema with arguments as
users:{
type: new GraphQLList(userType),
args: {
names: {
type: GraphQLString,
},
...connectionArgs,
},
resolve: (root, {names}) =>connectionFromArray(getUsers(names)),
},
but I got error Cannot read property 'after' of undefined in implementing react-relay
Thanks in Advance.
Relay currently only supports three types of root fields (see facebook/relay#112):
Root field without arguments, returning a single node:
e.g. { user { id } } returning {"id": "123"}
Root field with one argument, returning a single node:
e.g. { post(id: "456") { id } } returning {"id": "456"}
Root field with one array argument returning an array of nodes with the same size as the argument array (also known as "a plural identifying root field"):
e.g. { users(ids: ["123", "321"]) { id } } returning [{"id": "123"}, {"id": "321"}]
A workaround is to create a root field (often called viewer) returning a node that has those fields. When nested inside the Viewer (or any other node), fields are allowed to have any return type, including a list or connection. When you've wrapped the fields in this object in your GraphQL server, you can query them like this:
{
viewer {
users {
id,
fullName,
}
}
}
The Viewer type is a node type, and since there will just be one instance of it, its id should be a constant. You can use the globalIdField helper to define the id field, and add any other fields you want to query with Relay:
const viewerType = new GraphQLObjectType({
name: 'Viewer',
interfaces: [nodeInterface],
fields: {
id: globalIdField('Viewer', () => 'VIEWER_ID'),
users:{
type: new GraphQLList(userType),
resolve: (viewer) => getUsers(),
},
},
});
On the client you'll need to change the root query in your route to { viewer } and define the fragment on Viewer:
export default Relay.createContainer(UserList, {
fragments: {
viewer: () => Relay.QL`
fragment on Viewer {
users {
fullName,
local {
email,
},
images {
full,
},
currentPostCount,
isPremium,
}
}
`,
},
});

Resources