Parse.com REST How to query relation 3 table? - parse-platform

I am from MySQL so I design parse.com table like so
Vehicle | license, year, & pool_id
Pool | address & city_id
City | name
Pool_id in vehicle pointer to Pool,
City_id in pool pointer to city.
In mySQL we can Join three table and use where clause.
In the relational queries docs says
--data-urlencode 'where={"post":{"__type":"Pointer","className":"Post","objectId":"8TOXdXf3tz"}}'
Which query relation 1 table based on object id
How I query to get vehicle where city name = "somecity"?

In angularJS
var config = {
params: {
where: {
vehicle_year: "2013",
pool_id: {
$inQuery: {
where: {
city_id: {
$inQuery: {
where: {
city_name: "Jakarta"
},
className: "city"
}
}
//pool_address: "JL. DEF"
},
className: "pool"
}
},
car_id: {
$inQuery: {
where: {
car_class_id: {
$inQuery: {
where: {
name: "Box"
},
className: "car_class"
}
}
},
className: "car"
}
}
},
include: 'pool_id.city_id,car_id.car_class_id',
},
headers: { 'X-Parse-Application-Id' : 'gMKfl1wDyk3m6I5x0IrIjJyI87sumz58' }
};
then
$http.get('http://ip/parse/classname', config).then(function(response){
}, function(error){
});

Related

Query to get top 10 users from MongoDb in Spring

So basically I have a collection that looks like this(other fields omitted):
[{
user: mail1#test.com
},
{
user: mail1#test.com
},
{
user: mail1#test.com
},
{
user: mail2#test.com
},
{
user: mail2#test.com
},
{
user: mail3#test.com
}
]
I'm looking for a way to query MongoDB in order to get the top 10 active users(those with the most records in DB). Is there an easy way to get this, perhaps just using the interface?
perhaps a simple group aggregation will give you the needed result?
db.Users.aggregate(
[
{
$group: {
_id: "$user",
count: { $sum: 1 }
}
},
{
$sort: { count: -1 }
},
{
$limit: 10
},
{
$project: {
user: "$_id",
_id: 0
}
}
])
There is something called $sortByCount for aggregation.
List<UserCount> getTop10UserCount() {
return mongoTemplate.aggregate(
newAggregation(
User.class,
sortByCount("user"),
limit(10),
project("_id", "count")
),
UserCount.class
);
}
static class UserCount {
String _id;
Integer count;
// constructors, getters or setters..
}

Cannot pass custom result from resolver to Graphql

I am trying to fetch data with sequelize with an attribute and pass it to graphql.
The result is fine in console but the graphql query is returning null for the attribute field.
my resolver
getUnpayedLessons: async (_, args, { models }) => {
const { Attendance, Student } = models;
return await Attendance.findAll({
include: {
model: Student,
},
where: {
fk_lessonsSerieId: { [Op.is]: null },
},
attributes: ["id", [sequelize.fn("count", sequelize.col("absenceFlag")), "unpayedLessons"]],
group: ["student.id"],
});
},
query
getUnpayedLessons {
id
unpayedLessons
student {
id
firstName
lastName
}
}
schema
type UnpayedLessons {
id: Int
unpayedLessons: Int
student: Student
}
extend type Query {
getUnpayedLessons: [UnpayedLessons]
}
and this is the console.log of the resolver when I run the query
[
attendance {
dataValues: { id: 2, unpayedLessons: 8, student: [student] },
_previousDataValues: { id: 2, unpayedLessons: 8, student: [student] },
_changed: Set {},
_options: {
isNewRecord: false,
_schema: null,
_schemaDelimiter: '',
include: [Array],
includeNames: [Array],
includeMap: [Object],
includeValidated: true,
attributes: [Array],
raw: true
},
]
and from graphql
{
"data": {
"getUnpayedLessons": [
{
"id": 2,
"unpayedLessons": null,
"student": {
"id": 2,
"__typename": "Student"
},
"__typename": "UnpayedLessons"
},
]
}
}
Any idea how I can have unpayedLessons passed to graphql?
To debug this you need to check what is returned from DB, the shape:
const values = await Attendance.findAll({...
console.log( values );
// adapt structure to match query requirements
// finally return
return values;

Using multiple mutations in one call

I have written my first script that utilises GraphQL (Still a learning curve)
Currently i am making 3 calls using GraphQL,
First is a product lookup,
Second is a Price Update,
Third is a Inventory Update.
To reduce the number of calls to the end point i wanted to merge both Price update and Inventory, But i am having 0 luck, i dont know if its bad formatting.
Here is my GraphQL Code (I am using Postman to help ensure the schema is correct before taking it to PHP)
mutation productVariantUpdate($input: ProductVariantInput!) {
productVariantUpdate(input: $input) {
product {
id
}
productVariant {
id
price
}
userErrors {
field
message
}}
second: inventoryActivate($inventoryItemId: ID!, $locationId: ID!, $available: Int) {
inventoryActivate(inventoryItemId: $inventoryItemId, locationId: $locationId, available: $available) {
inventoryLevel {
id
available
}
userErrors {
field
message
}
}
}
}
Variables:
{
"inventoryItemId": "gid://shopify/InventoryItem/XXXXXXXXXXX",
"locationId": "gid://shopify/Location/XXXXXXXXXX",
"available": 11 ,
"input": {
"id": "gid://shopify/ProductVariant/XXXXXXXXX",
"price": 55
}
}
Error i keep getting:
{
"errors": [
{
"message": "Parse error on \"$\" (VAR_SIGN) at [29, 29]",
"locations": [
{
"line": 29,
"column": 29
}
]
}
]
}
The way that you'd go about this is by specifying all your arguments at the root of your mutation, just like you did for ProductVariantInput:
mutation batchProductUpdates(
$input: ProductVariantInput!
$inventoryItemId: ID!
$locationId: ID!
$available: Int
) {
productVariantUpdate(input: $input) {
product { id }
productVariant { id price }
...
}
inventoryActivate(
inventoryItemId: $inventoryItemId
locationId: $locationId
available: $available
) {
inventoryLevel { id available }
...
}
}
Here's an example how this would work if you were to use fetch in JavaScript:
fetch("https://example.com/graphql", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
query: `
mutation MyMutation($firstId: Int, $secondId: Int) {
m1: ToggleLike(id: $firstId) {
id
}
m2: ToggleLike(id: $secondId) {
id
}
}
`,
variables: {
firstId: 1,
secondId: 2
}
})
})
Hope this helps.

Prisma binding Nested filtering

I'm working on a food order platform with Prisma, Prisma-binding and Apollo Server on the backend. A customer can choose a restaurant in his neighbourhood and add one or more dishes to his cart. It is possible that when a dish from restaurant x is already added, the customer decides to order from another restaurant, restaurant y. Therefore I need to filter the added dishes when making an order based on the customer id and the final chosen restaurant in the backend first before creating the order and payment url.
I've got three data types inside my prisma datamodel: Customer, CartItem and Dish
type Customer {
id: ID! #id
createdAt: DateTime! #createdAt
updatedAt: DateTime! #updatedAt
name: String
email: String
phone: String
user: User
cart: [CartItem]!
orders: [Order]!
}
type CartItem {
id: ID! #id
quantity: Int! #default(value: 1)
dish: Dish!
customer: Customer! #relation(link: INLINE)
}
type Dish {
id: ID! #id
name: String!
price: String!
description: String!
isAvailable: Boolean! #default(value: true)
category: String
restaurant: Restaurant!
}
In the Prisma GraphQL playground that is directly connected to the database I can filter the cartItems that I need to create the order like this:
query {
customer(where: { id: "ck8zwslgs00da0712cq88e3oh" } ) {
id
cart(where: { dish: { restaurant: { id: "ck904gwl400mz0712v0azegm3" } } }) {
quantity
dish {
name
price
restaurant {
id
name
}
}
}
}
}
output:
{
"data": {
"customer": {
"id": "ck8zwslgs00da0712cq88e3oh",
"cart": [
{
"quantity": 2,
"dish": {
"name": "Nachos Plate Hawaii",
"price": "1150",
"restaurant": {
"id": "ck904gwl400mz0712v0azegm3",
"name": "Taco Bell"
}
}
},
{
"quantity": 1,
"dish": {
"name": "Nachos Plate Vulcano",
"price": "1250",
"restaurant": {
"id": "ck904gwl400mz0712v0azegm3",
"name": "Taco Bell"
}
}
}
]
}
}
}
So far so good but now I need the same query in the Apollo Server using prisma-binding. I tried a few things but none of them are working. The first two are returning an error "Field \"cart\" is not defined by type CustomerWhereUniqueInput". The last two are just returning every cartItem without the restaurant filter.
const data = await ctx.db.query.customer({
where: {
AND: [
{
id: args.customerID
},
{
cart: {
dish : {
restaurant: {
id: args.restaurantID
}
}
}
}
]
}
}, info);
const data = await ctx.db.query.customer({
where: {
id: args.customerID
cart: {
dish : {
restaurant: {
id: args.restaurantID
}
}
}
}
}, info);
const data = await ctx.db.query.customer({
where: {
id: args.customerID
},
cart: {
where: {
dish : {
restaurant: {
id: args.restaurantID
}
}
}
}
}, info);
const data = await ctx.db.query.customer({
where: {
id: args.customerID
},
cart: {
dish : {
restaurant: {
where: {
id: args.restaurantID
}
}
}
}
}, info);
Can someone help me out with the right way to filter on the customer id and the restaurant id?

how to set many-to-many relation in graphql mutation?

I may be missing something, but can not find any information on Apollo docs about the way to set a many-to-many relation when creating a new entry.
When the relation is one-to-many it is as simple as setting the ID of the one-side of the relationship in the many-side object.
But let's pretend I am working with Books and Authors, how would I write a graphql query that creates a Book for one (or many?) Authors?
This should probably happen at the API layer on the GraphQL server (i.e. schema). For many-to-many relationships, you should have a "join" type to denote the BookAuthor many-to-many relationship, and then add an entry to that join type.
Essentially then you'll have a type called Book, another called Author, and finally one more called BookAuthor. And you can add a few mutations to be able to manage that relationship. Perhaps...
addToBookAuthorConnection
updateBookAuthorConnection
removeFromBookAuthorConnection
This is a conventional setup using a Relay-spec compliant API. You can read more about how to structure your API for many-to-many relationships here.
Then, you only need to call the addToBookAuthorConnection mutation from Apollo instead to be able to add to that many-to-many connection on your frontend.
Hope this helps!
If u r using apollo graph server with one to many relations then connectors.js, resolvers.js and schema.js files as given formats
schema.js
const typeDefinitions = `
type Author {
authorId: Int
firstName: String
lastName: String
posts: [Post]
}
type Post {
postId: Int
title: String
text: String
views: Int
author: Author
}
input postInput{
title: String
text: String
views: Int
}
type Query {
author(firstName: String, lastName: String): [Author]
posts(postId: Int, title: String, text: String, views: Int): [Post]
}
type Mutation {
createAuthor(firstName: String, lastName: String, posts:[postInput]): Author
updateAuthor(authorId: Int, firstName: String, lastName: String, posts:[postInput]): String
}
schema {
query: Query
mutation:Mutation
}
`;
export default [typeDefinitions];
resolvers.js
import { Author } from './connectors';
import { Post } from './connectors';
const resolvers = {
Query: {
author(_, args) {
return Author.findAll({ where: args });
},
posts(_, args) {
return Post.findAll({ where: args });
}
},
Mutation: {
createAuthor(_, args) {
console.log(args)
return Author.create(args, {
include: [{
model: Post,
}]
});
},
updateAuthor(_, args) {
var updateProfile = { title: "name here" };
console.log(args.authorId)
var filter = {
where: {
authorId: args.authorId
},
include: [
{ model: Post }
]
};
Author.findOne(filter).then(function (product) {
Author.update(args, { where: { authorId: args.authorId } }).then(function (result) {
product.posts[0].updateAttributes(args.posts[0]).then(function (result) {
//return result;
})
});
})
return "updated";
},
},
Author: {
posts(author) {
return author.getPosts();
},
},
Post: {
author(post) {
return post.getAuthor();
},
},
};
export default resolvers;
connectors.js
import rp from 'request-promise';
var Sequelize = require('sequelize');
var db = new Sequelize('test', 'postgres', 'postgres', {
host: '192.168.1.168',
dialect: 'postgres',
pool: {
max: 5,
min: 0,
idle: 10000
}
});
const AuthorModel = db.define('author', {
authorId: { type: Sequelize.INTEGER, primaryKey: true, autoIncrement: true, field: "author_id" },
firstName: { type: Sequelize.STRING, field: "first_name" },
lastName: { type: Sequelize.STRING, field: "last_name" },
},{
freezeTableName: false,
timestamps: false,
underscored: false,
tableName: "author"
});
const PostModel = db.define('post', {
postId: { type: Sequelize.INTEGER, primaryKey: true, autoIncrement: true, field: "post_id" },
text: { type: Sequelize.STRING },
title: { type: Sequelize.STRING },
views: { type: Sequelize.INTEGER },
},{
freezeTableName: false,
timestamps: false,
underscored: false,
tableName: "post"
});
AuthorModel.hasMany(PostModel, {
foreignKey: 'author_id'
});
PostModel.belongsTo(AuthorModel, {
foreignKey: 'author_id'
});
const Author = db.models.author;
const Post = db.models.post;
export { Author, Post };

Resources