GraphQL query returns an empty array on many-to-many relation - Prisma-Pothos - next.js

I've been struggling for some days now and feel dumb. I'm new to GraphQL and Prisma.
I'm creating a simple CRUD app with Next.js, GraphQL-Yoga, Prisma, Pothos, Apollo-Client and auth0. I use supabase for a PostgreSQL database. I want to query the posts and the corresponding user for each post. So I can map over it in react and display for example the role and the email of each user next to their post. I made a many-to-many relationship in the schema.prisma.
I tried using a one-to-many relation but I could only get, for example, the id, not the id and the email simultaneously.
GraphQL-Playground query:
query MyQuery {
posts {
title
id
user {
email
id
}
}
}
The user remains empty. Output:
{
"data": {
"posts": [
{
"title": "Lettuce",
"id": "1",
"user": []
},
{
"title": "Banana",
"id": "2",
"user": []
},
{
"title": "Carrot",
"id": "3",
"user": []
}
]
}
}
// /prisma/schema.prisma:
model User {
id String #id #default(uuid())
createdAt DateTime #default(now())
updatedAt DateTime #updatedAt
email String? #unique
image String?
role Role #default(USER)
Posts Post[]
}
model Post {
id String #id #default(uuid())
createdAt DateTime #default(now())
updatedAt DateTime #updatedAt
title String
description String
category String
User User[]
}
// /graphQL/types/Post.ts
import { builder } from "../builder";
builder.prismaObject("Post", {
fields: (t) => ({
id: t.exposeID("id"),
title: t.exposeString("title"),
description: t.exposeString("description"),
category: t.exposeString("category"),
user: t.relation("User"),
}),
});
builder.queryField("posts", (t) =>
t.prismaField({
type: ["Post"],
resolve: (query, _parent, _args, _ctx, _info) =>
prisma.post.findMany({
...query,
}),
})
);
It seems like this is what I need but when I integrate the <builder.queryType> portion I get an error saying:
PothosSchemaError: Duplicate typename: Another type with name Query already exists.
I tried some other things and got nothing. It seems like REST is so much easier.

Related

can dynamodb query for data with a list contains object that match some attribute?

can dynamodb query data for list contains object that match some attribute?
my data format:
[{
pk,
sk,
gsi1pk: 'USER',
gsi1sk,
list:[
{
id,
type, // admin, moderator, user
name,
}
]
}]
can we do something like this to find data with list contains type is 'admin'?
await Ddb.query( {
IndexName: 'GSI1',
KeyConditionExpression: 'gsi1pk = :gsi1pk',
FilterExpression: 'contains(list, :list)'
ExpressionAttributeValues: {
':gsi1pk': 'USER',
':list': { type: 'admin'}
},
});
this does not work now :(

Facing issue while trying to run the updateitem in dynamo db

I am able to fetch the record from dynamo db and view the response successfully. I need to modify the fetched 'ACCOUNTNAME' attribute in the 'items' array and update the json and also update in dynamo db. Now when I try to update the fetched records I end up with the Invalid attribute value type exception.
I was trying to update it using the key with Array of Strings which is provided with code snippet also tried to update inside for loop using the individual string but both failed with same exception as
"statusCode": 400,
"body": {
"message": "Invalid attribute value type",
"error": {
"errorMessage": "ValidationException"
}
}
I tried to create params and update the call inside the for loop by setting the key as below,
Key: {
"UUID": {
"S": usersOfAccountFromDB.body.Items[key].UUID
}
,
"TYPE": {
"S": user
}
}
but also failed with the same exception.
Fetched Json from dynamo db
[
{
"DEFINITION": "914ba44a-8c26-4b60-af0f-96b6aa37efe6",
"UUID": "830a49cb-4ed3-41ae-b111-56714a71ab98",
"TYPE": "USER",
"RELATION": "01efd131-6a5d-4068-889e-9dba44262da5",
"ACCOUNTNAME": "Wolff LLC"
},
{
"DEFINITION": "1f60fded-323d-40e1-a7f8-e2d053b0bed0",
"UUID": "47db3bbe-53ac-4e58-a378-f42331141997",
"TYPE": "USER",
"RELATION": "01efd131-6a5d-4068-889e-9dba44262da5",
"ACCOUNTNAME": "Wolff LLC"
},
{
"DEFINITION": "05ddccba-2b6d-46bd-9db4-7b897ebe16ca",
"UUID": "e7290457-db77-48fc-bd1a-7056bfce8fab",
"TYPE": "USER",
"RELATION": "01efd131-6a5d-4068-889e-9dba44262da5",
"ACCOUNTNAME": "Wolff LLC"
},
.
.
.
.]
Now I tried to iterate the Json and setup UUID which is the key as the String array as below,
var userUUIDArray : string[] = [];
for (let key in usersOfAccountFromDB.body.Items) {
userUUIDArray.push(usersOfAccountFromDB.body.Items[key].UUID);
}
for (var uuid of userUUIDArray) {
console.log("UUID : " +uuid); // prints all the uuid
}
// Creating a parameter for the update dynamo db
var params = {
TableName: <tableName>,
Key: {
"UUID": {
"SS": userUUIDArray
}
,
"TYPE": {
"S": user
}
},
UpdateExpression: 'SET #ACCOUNTNAME = :val1',
ExpressionAttributeNames: {
'#ACCOUNTNAME': 'ACCOUNTNAME' //COLUMN NAME
},
ExpressionAttributeValues: {
':val1': newAccountName
},
ReturnValues: 'UPDATED_NEW',
};
//call the update of dynamodb
const result = await this.getDocClient().update(param).promise();
I get the error as below,
"body": {
"message": "Invalid attribute value type",
"error": {
"errorMessage": "ValidationException"
}
}
All the approaches failed with same above exception
The update operation which your code currently uses only allow a single item to be updated.
IIUC, you want to update multiple items with one API call. For this you need to use batchWrite operation. Keep in mind that you cannot update more than 25 items per invocation.
The origin of the error you are getting
Your code fails due to the use of "SS" in the UUID field. This field is of type string so you must use "S". Note however that since you're using the document client API you do not need to pass values using this notation. See this answer for further details.
I have resolved the issue now by running the update statement one by one using loop
for (let key in usersOfAccountFromDB.body.Items) {
var updateParam = {
TableName: process.env.AWS_DYNAMO_TABLE,
Key: {
UUID: usersOfAccountFromDB.body.Items[key].UUID,
TYPE: user
},
UpdateExpression: "SET #ACCOUNTNAME = :val1",
ExpressionAttributeNames: {
'#ACCOUNTNAME': 'ACCOUNTNAME'
},
ExpressionAttributeValues: {
":val1": newAccountName
},
ReturnValues: "UPDATED_NEW",
};
const result = await this.getDocClient().update(updateParam).promise();
}

React Native Firebase database Join or other way for Join

First of all I know NOSQL systems do not have JOIN. But I know there is a way for getting a datas with another table values.
About my app:
This app is basic social network app. People can share photos. These posts saving firebase database 'realtime database' not cloud firestore than it has a timeline page. this page shows shared posts. I need to show posts with publisher information.
Users login with firebase authentication and I have users table called kullanici like this.
I have Posts table like this.
I need to delete displayName in Posts table than get isim in kullanici table.
my needed data is: Post with kullanici->{posts.{postid}.userid}->isim.
my working code is below:
return (dispatch) => {
firebase.database().ref(`/posts`).endAt("tarih").limitToLast(2)
.on('value', snapshot => {
dispatch({type: STUDENT_LIST_DATA_SUCCESS, payload: snapshot.val()});
});
};
my returned data is below:
Object {
"-L9tnfvm6jQiKLc378c6": Object {
"aciklama": "",
"baslik": "Ensar mı Ahmet mi",
"displayName": "HasanRiza",
"image": "https://hasan-riza-uzuner.s3.amazonaws.com/1523535677033.png",
"like": 244,
"tarih": 1523535757133,
"userid": "fD7IfKAhXogFwHtfKYiF7LMtXNp1",
},
"-LYHPJgR4sywTzpcxX7A": Object {
"aciklama": "Ev",
"baslik": "Nasıl",
"displayName": "HasanRiza",
"image": "https://hasan-riza-uzuner.s3.us-east-2.amazonaws.com/1549718296409.png",
"like": 1,
"tarih": 1549718342522,
"userid": "fD7IfKAhXogFwHtfKYiF7LMtXNp1",
},
}
var promises = [];
group_ids.forEach(function (group_id) {
promises.push(firebase.firestore().collection('Group').doc(group_id).get())
});
Promise.all(promises).then(function(docs) {
docs.forEach((groupDoc) => {
group.name = groupDoc._data['name'];
group.city = groupDoc._data['city'];
group.state = groupDoc._data['state'];
groups.push(group);
});
console.log(groups);
});

AWS AppSync GraphQL query a record by a field value

I have an user table, which consists of email, phone etc., and I would like to query a record based on its email or phone value (instead of #Id). Having not-adequate knowledge to do this - I wrote a schema like this:
type Query {
...
getUser(id: ID!): User
getUserByEmail(input: GetUserByEmailInput!): User
...
}
input GetUserByEmailInput {
email: String!
}
In resolver against getUserByEmail(..), I tried to experiment but nothing worked so far, so its remain to default state:
So when I ran a query like this to the Queries console:
query GetUserByEmail {
getUserByEmail(input: {email: "email#email.com"}) {
id
name
email
image
}
}
this returns an error like this:
{
"data": {
"getUserByEmail": null
},
"errors": [
{
"path": [
"getUserByEmail"
],
"data": null,
"errorType": "DynamoDB:AmazonDynamoDBException",
"errorInfo": null,
"locations": [
{
"line": 41,
"column": 5,
"sourceName": null
}
],
"message": "The provided key element does not match the schema (Service: AmazonDynamoDBv2; Status Code: 400; Error Code: ValidationException; Request ID: xxx)"
}
]
}
How can I query a record by non-Id field value?
If you use the Create Resources flow in the console, it will create a listUsers query that looks like the following for example. Note that the DynamoDb operation will be a Scan that has a DynamoDb filter expression where you can use any field to query DynamoDb. See below for the mapping template.
{
"version": "2017-02-28",
"operation": "Scan",
"filter": #if($context.args.filter) $util.transform.toDynamoDBFilterExpression($ctx.args.filter) #else null #end,
"limit": $util.defaultIfNull($ctx.args.limit, 20),
"nextToken": $util.toJson($util.defaultIfNullOrEmpty($ctx.args.nextToken, null)),
}
You can find more details about Scans and filter expressions in the AWS AppSync documentation:
https://docs.aws.amazon.com/appsync/latest/devguide/tutorial-dynamodb-resolvers.html

How can we log Custom Activity data against leads with Marketo REST API?

We have created a Custom Activity with Marketo web portal, and we are able to create leads with REST API. So now, how can we log Custom Activity data using Marketo REST API?
Custom Activity structure is as follows:
{
"id": 100001,
"name": "TEST_ACTIVITY",
"apiName": "test_api_c",
"description": "",
"primaryAttribute": {
"name": "event_id",
"apiName": "event_id",
"dataType": "string"
},
"attributes": [
{
"name": "email",
"apiName": "email",
"dataType": "email"
},
{
"name": "event_data",
"apiName": "event_data",
"dataType": "string"
}
]
}
You can push your custom activity records to the Add Custom Activities endpoint, which is available at the POST /rest/v1/activities/external.json url.
First, worth to note, that in order to use the endpoint, the API user has to have the “Read-Write Activity” permission.
The endpoint expects a payload with a single input key, that can hold up to 300 activity records. For each activity record the leadId, activityDate, activityTypeId, primaryAttributeValue and attributes fields are required, and in case of the attributes array, the name is the normal “name” field, not the “apiName”.
In your case the payload would look something like this:
{
"input":[// Note the array of records
{
"activityDate":"2018-03-20T22:43:12+02:00",
"activityTypeId":100001,
"leadId":<LEAD_ID>,
"primaryAttributeValue":"<YOUR_EVENT_ID>",
"attributes":[
{
"name":"email",// This is the `name` field of the attribute, not the `apiName`!
"value":"<EMAIL_ADDRESS>"
},
{
"name":"event_data",// This is the `name` field of the attribute, not the `apiName`!
"value":"<EVENT_DATA>"
}
]
},
//{
// …other activity records…
//}
]
}

Resources