AWS AppSync - Implement many to many connections using 1-M #connections and a joining #model - database

Following AWS documentation (https://aws-amplify.github.io/docs/cli-toolchain/graphql > Many-To-Many Connections), I try to understand the workaround example they provide for many to many connections (which seems not supported yet by Amplify).
The schema is:
type Post #model {
id: ID!
title: String!
editors: [PostEditor] #connection(name: "PostEditors")
}
# Create a join model and disable queries as you don't need them
# and can query through Post.editors and User.posts
type PostEditor #model(queries: null) {
id: ID!
post: Post! #connection(name: "PostEditors")
editor: User! #connection(name: "UserEditors")
}
type User #model {
id: ID!
username: String!
posts: [PostEditor] #connection(name: "UserEditors")
}
Using AWS AppSync Console, so far I'm able to:
Create a user using this mutation:
mutation {
createUser(input:{
username: "theUserName"
}){
username
}
}
Create a post using this mutation:
mutation {
createPost(input: {
title: "second post"
}){
title
}
}
But I don't understand how to add multiple editors to a post? So far, I'm able to add editors to a post using PostEditor join, but in their example, there is this statement (which I don't understand very well), so I don't think this is the good approach:
# Create a join model and disable queries as you don't need them
# and can query through Post.editors and User.posts
So I guess that using this join model to perform mutation is not what I have to do. Nevertheless, to be able to create this relation between a post and an editor, I created a mutation (retrieving "postEditorPostId" and "postEditorEditorId" from both previous mutations):
mutation {
createPostEditor(input:{
postEditorPostId: "XXX-XXX-XXX"
postEditorEditorId: "YYY-YYY-YYY"
}){
post {
title
}
editor {
username
posts {
items {
post {
title
}
}
}
}
}
}
Do I need to perform this previous mutation everytime I add a new editor (so the mutation will remain the same but "postEditorEditorId" will change? it seems obviously not a scalable approach, if for example the UI allows an admin to add 50 or more new editors (so it will need 50 mutations).
Finally I can get the information I need using this query:
query{
getUser(id: "YYY-YYY-YYY"){
username
posts {
items {
post {
title
}
}
}
}
}
Is there a better way (I suppose) to add editors to a post?
edit:
Using a promise, I am able to add multiple editors to a post, but it involves to execute as mutation as mutations as there are users:
const users = [{id: "U1", username: "user1"}, {id: "U2", username: "user2"}];
const post = { id: "P1", title: "Post 1" };
/*
After creating two users and a post using the approriate mutations
Using the CreatePost join below to make user1 and user2 editor on Post 1
*/
function graphqlCreatePostEditor(editorID) {
return new Promise((resolve, reject) => {
resolve(
API.graphql(graphqlOperation(createPostEditor, {
input: {
postID: post.id,
}
}))
)
})
}
let promises = users.map(user=> {
return graphqlCreatePostEditor(user.id)
.then(e => {
console.log(e)
return e;
})
});
Promise.all(promises)
.then(results => {
console.log(results)
})
.catch(e => {
console.error(e);
})
Still looking if there is a way to pass an array in a sigle mutation.

For simplicity sake, I'm lets go with a User model and a Project model where a user can have many projects and belong to many projects.
Note: The creation of join table as I've described it here is for the Amplify JS API for React / React Native / JavaScript
User model
type User #model {
id: ID!
username: String!
projects: [UserProject] #connection(name: "UserProject")
}
Project model
type Project #model {
id: ID!
project_title: String!
users: [UserProject] #connection(name: "ProjectUser")
}
Join table
type UserProject #model {
id: ID!
user: User #connection(name: "UserProject")
project: Project #connection(name: "ProjectUser")
}
Creation of Join table
Prerequisite: Fetch both user.id and project.id however you want to do that.
const UserProjectDetails = {
userProjectUserId: user.id
userProjectProjectId: project.id
};
API.graphql({ query: mutations.createUserProject, variables: {input: UserProjectDetails}})
And there you have it.
This article on dev.to was also pretty straight to the point:
https://dev.to/norrischebl/modeling-relationships-join-table-graphql-aws-amplify-appsync-1n5f

Related

Why is amplify saving username incorrectly?

I have a function to create a vehicle in my amplify project:
const createNewVehicle = async () => {
const { year, make, model, vinNumber } = searchedVehicleInfo || {};
try {
await API.graphql({
query: createVehicle,
variables: { input: { year, make, model, vinNumber } },
authMode: 'AMAZON_COGNITO_USER_POOLS',
});
} catch (err) {
console.log(err);
return null;
}
};
This function creates a vehicle in my dynamoDB table utilizing the API module exposed by amplify. The authMode property saves the Cognito user's username in the API request as well. The vehicle's graphql model looks like this:
type Vehicle
#model
#auth(
rules: [
{
allow: owner
ownerField: "username"
operations: [create, read, update, delete]
}
{ allow: public, operations: [read] }
]
) {
id: ID!
year: Int!
make: String!
model: String!
vinNumber: String!
image: String
username: String
#index(name: "vehiclesByUsername", queryField: "vehiclesByUsername")
receipts: [Receipt] #hasMany(indexName: "byVehicle", fields: ["id"])
}
A team member created his own AWS account and set up his own environment to be used in amplify. This team member created an IAM user and applied the AdminAccess-Amplify role to his user. When he uses this function, the vehicle is created, but it saves the username in a weird way. If his username is test12 it will save the vehicle with a username like this 6e0b3347-5dae-4106-aed6-8ec5c87fde52::test12. So when I try to grab vehicles by username, none come up because his username is test12 and not 6e0b3347-5dae-4106-aed6-8ec5c87fde52::test12.
How can I get it to save just the username and not all the extra information?

Stripe webhook checkout.session items to Supabase

Im using next.js and Stripe webhooks to insert checkout sessions to Supabase that will create a customer's order history. I'm able to get the information about the whole order written to a table called 'orders', but am wondering what the best way to add individual items within each checkout session to another table called 'order_items' is. This way I can map through main orders and then the children items. Appreciate any help provided. Here is what I have for getting orders associated with a customer:
const upsertOrderRecord = async (session: Stripe.Checkout.Session, customerId: string) => {
const { data: customerData, error: noCustomerError } = await supabaseAdmin
.from<Customer>('customers')
.select('id')
.eq('stripe_customer_id', customerId)
.single();
if (noCustomerError) throw noCustomerError;
const { id: uuid } = customerData || {};
const sessionData: Session = {
id: session.id,
amount_total: session.amount_total ?? undefined,
user_id: uuid ?? undefined
};
const { error } = await supabaseAdmin.from<Session>('orders').insert([sessionData], { upsert: true });
if (error) throw error;
console.log(`Product inserted/updated: ${session.id}`);
};
The Checkout Session object contains a line_items field which is a list of each item included in the purchase.
However this field is not included in the object by default, and therefore won't be a part of your webhook payload. Instead you'll need to make an API call in your webhook handle to retrieve the Checkout Session object, passing the expand parameter to include the line_items field:
const session = await stripe.checkout.sessions.retrieve('cs_test_xxx', {
expand: ['line_items']
});

Posting to mongoDb with ObjectId Many to one relationship

Mongoose/MongoDB Question
I have an Owners model containing basic profile data.
I have a secondary model: OwnersImages
e.g
{
owner: {
type: Schema.Types.ObjectId,
ref: 'Owners'
},
name: String,
imageUrl: String,
},
);
From the client I want to post the imageUrl and the name to the OwnersImages table.
e.g
let values = {
owner: this.state.user._id,
name: this.state.field,
imageUrl: this.state.url
}
axios.post(`${serverPath}/api/addFieldImage`, values)
However Im unsure how best to go about this, link it etc.
I can do a GET request on the Owners table to get the Owner data, but then posting this as part of the values to OwnerImages doesn't successfully link the two tables.
Do i need to just store a string reference to the Owner id in OwnerImages or is there a smarter way of doing this?
Or should I just post the string of the user Id to mongoose and then do a map to the Owner table from within there?
Tried to explain this best way I could but the eyes are tired so please ask if any confusion!
Many thanks
Without seeing your exact setup, I think you could modify this to fit your needs:
// In the Schema/Model files
const ownersSchema = Schema({
// other fields above...
images: [{ type: Schema.Types.ObjectId, ref: 'OwnersImages' }]
});
const ownersImagesSchema = Schema({
// other fields above...
owner: { type: Schema.Types.ObjectId, ref: 'Owners' },
});
// in the route-handler
Owners.findById(req.body.owner, async (err, owner) => {
const ownersImage = new OwnersImages(req.body);
owner.images.push(ownersImage._id);
await ownersImage.save();
await owner.save();
});
As a side-note, I think the Models generally have singular names, so Owner and OwnerImage. The collection will then automatically take on the plural form. Just food for thought.
When you want to load these, you can link them with populate(). Consider loading all of the OwnersImages associated with an Owners in some route-handler where the /:id param is the Owners id:
Owners
.findOne({ _id: req.params.id })
.populate('images')
.exec(function (err, images) {
if (err) return handleError(err);
// do something with the images...
});

Handling Users with MongoDB Stitch App within Atlas Cluster

I have an MongoDB Stitch app, that users the Email/Password authentication. This creates users within the Stitch App that I can authenticate on the page. I also have an MongoDB Atlas Cluster for my database. In the cluster I have a DB with the name of the project, then a collection underneath that for 'Matches'. So when I insert the 'Matches' into the collection, I can send the authenticated user id from Stitch, so that I have a way to query all Matches for a particular User. But how can I add additional values to the 'User' collection in stitch? That user section is sort of prepackaged in Stitch with whatever authentication type you choose (email/password). But for my app I want to be able to store something like a 'MatchesWon' or 'GamePreference' field on the 'User' collection.
Should I create a collection for 'Users' the same way I did for 'Matches' in my Cluster and just insert the user id that is supplied from Stitch and handle the fields in that collection? Seems like I would be duplicating the User data, but I'm not sure I understand another way to do it. Still learning, I appreciate any feedback/advice.
There isn't currently a way to store your own data on the internal user objects. Instead, you can use authentication triggers to manage users. The following snippet is taken from these docs.
exports = function(authEvent){
// Only run if this event is for a newly created user.
if (authEvent.operationType !== "CREATE") { return }
// Get the internal `user` document
const { user } = authEvent;
const users = context.services.get("mongodb-atlas")
.db("myApplication")
.collection("users");
const isLinkedUser = user.identities.length > 1;
if (isLinkedUser) {
const { identities } = user;
return users.updateOne(
{ id: user.id },
{ $set: { identities } }
)
} else {
return users.insertOne({ _id: user.id, ...user })
.catch(console.error)
}
};
MongoDB innovates at a very fast pace - and while in 2019 there wasn't a way to do this elegantly, now there is. You can now enable custom user data on MongoDB realm! (https://docs.mongodb.com/realm/users/enable-custom-user-data/)
https://docs.mongodb.com/realm/sdk/node/advanced/access-custom-user-data
const user = context.user;
user.custom_data.primaryLanguage == "English";
--
{
id: '5f1f216e82df4a7979f9da93',
type: 'normal',
custom_data: {
_id: '5f20d083a37057d55edbdd57',
userID: '5f1f216e82df4a7979f9da93',
primaryLanguage: 'English',
},
data: { email: 'test#test.com' },
identities: [
{ id: '5f1f216e82df4a7979f9da90', provider_type: 'local-userpass' }
]
}
--
const customUserData = await user.refreshCustomData()
console.log(customUserData);

Add filtering option to the graphql paginated query

I am using this nice apollo-universal-starter-kit in one of my projects. I have a task to add a filtering option to this page to filter posts that have more than 2 comments.
The starter kit uses Apollo graphql-server as the back-end. The schema description for the posts looks like this:
# Post
type Post {
id: Int!
title: String!
content: String!
comments: [Comment]
}
# Comment
type Comment {
id: Int!
content: String!
}
# Edges for PostsQuery
type PostEdges {
node: Post
cursor: Int
}
# PageInfo for PostsQuery
type PostPageInfo {
endCursor: Int
hasNextPage: Boolean
}
# Posts relay-style pagination query
type PostsQuery {
totalCount: Int
edges: [PostEdges]
pageInfo: PostPageInfo
}
extend type Query {
# Posts pagination query
postsQuery(limit: Int, after: Int): PostsQuery
# Post
post(id: Int!): Post
}
postsQuery is used to generate a paginated result of the posts
Here is how postsQuery resolves (complete code here)
async postsQuery(obj, { limit, after }, context) {
let edgesArray = [];
let posts = await context.Post.getPostsPagination(limit, after);
posts.map(post => {
edgesArray.push({
cursor: post.id,
node: {
id: post.id,
title: post.title,
content: post.content,
}
});
});
let endCursor = edgesArray.length > 0 ? edgesArray[edgesArray.length - 1].cursor : 0;
let values = await Promise.all([context.Post.getTotal(), context.Post.getNextPageFlag(endCursor)]);
return {
totalCount: values[0].count,
edges: edgesArray,
pageInfo: {
endCursor: endCursor,
hasNextPage: values[1].count > 0
}
};
}
And, here is a graphql query which is used on the front-end with React post_list component (complete code for the component is here)
query getPosts($limit: Int!, $after: ID) {
postsQuery(limit: $limit, after: $after) {
totalCount
edges {
cursor
node {
... PostInfo
}
}
pageInfo {
endCursor
hasNextPage
}
}
}
This was a long introduction :-), sorry
Question:
How can I add filtering option to the post_list component/page? I kind of understand the React side of the question, but I do not understand the graphql one. Should I add a new variable to the postsQuery(limit: $limit, after: $after) so it looks like postsQuery(limit: $limit, after: $after, numberOfComments: $numberOfComments)? And then somehow resolve it on the back-end? Or, I am on the wrong track and should think in the different direction? If so, can you point me to the right direction? :-)
Thank you in advance!
IMO I would definitely solve this on the backend. As far as whether or not it should be a new variable, i personally would say yes, and your Post.getPostsPagination could be updated to support filtering on comment count, ideally you want that as part of the DB request so that you know you are getting N number of the types of posts you want, otherwise it will open up the door for edgecases in your pagination.
The other option is a new query for CuratedPosts, or FilteredPosts, or whatever you want to call it that already knows to filter based on number of comments.

Resources