How to add multiple ids to a connect on Prisma - node.js

Reading the prisma docs i find that is possible to create a connection where i make the plan have one item connected (as i did below). but i want to dinamic pass an array of strings (that items prop) that have ids of items to connect when creating my plan.
The code below works well, but i dont know how to pass that array n connect every item that match one of the ids on the array
const plan = await this.connection.create({
data: {
name,
description,
type,
picture,
productionPrice,
price,
items: {
connect: [
{
id: items,
},
],
},
},
include: {
items: true,
},
});
return plan;

I think, you have to provide an array like this:
const plan = await this.connection.create({
data: {
name,
description,
type,
picture,
productionPrice,
price,
items: {
connect: [
{
id: 1,
},
{
id: 2,
},
{
id: 3,
},
],
},
},
include: {
items: true,
},
});
If items contains a list of IDs, you can use:
...
items: {
connect: items.map(id => ({ id }),
},
...

Related

Prisma contains clause in where on array of strings

I have the following request payload which is passed as values for filters
filters: {
"name": ["Joh", "Matt"]
}
Consider that this is the data that I have in the database
name
____
John
Jane
Is there a way in Prisma by which I can return partial matches based on any of the filter values in the array (in this case return John)
I have been passing the following filter object the where clause for single filter values but not sure how to do it when I have multiple values/array to check for
name: {
contains: filters.name,
mode: "insensitive",
}
Given that we create the user table with name column that has two rows like below:
const user = await prisma.user.createMany({
data: [
{
name: "John"
},
{
name: "Jane"
}
]
});
To search for multiple values, you would do something like below:
const getUser = await prisma.user.findMany({
where:{
OR: [
{
name: {
contains: 'Joh',
},
},
{
name: {
contains: 'Matt',
},
},
]
},
})
console.log(getUser);
The output is
[ { id: 4, name: 'John' } ]
To learn more about search, check out the prisma docs

How do I update a nested list data in dynamodb using serverless stack?

I have a dynamoDB table that has an Item that includes a user and a List of plans. It looks like this:
Item:
{
user: 'abc123',
plans: [
{
id: 1,
name: 'movies',
category: 'category',
price: 200,
},
{
id: 2,
name: 'fishing',
category: 'category2',
price: 400,
}
]
}
Now, I want to update only id:2's object(name, category, price) in the List. So I wrote the handler below. And there is an error edit error ValidationException: The document path provided in the update expression is invalid for update in CloudWatch.
export const processAddPlan = async (event:APIGatewayEvent) => {
const data = JSON.parse(event.body)
const { store, id } = event.queryStringParameters
const params = {
TableName: usersTable,
Key: {
store: store,
id: id,
},
UpdateExpression: 'SET #pl[1] = :plans',
ExpressionAttributeNames: {
'#pl' : 'plans',
},
ExpressionAttributeValues: {
':plans': [
{
'name': data.planName,
'category': data.planCategory,
'price': data.planPrice,
},
],
},
ReturnValues: 'UPDATED_NEW',
}
log.info('params', params)
await dynamoDb.update(params).catch(e => log.info('edit error', e))
return success('edit plan succeeded')
}
I set query params and I tested(send) by postman like this.
{
"plans":[
{"planName":"ga2new",
"planCategory": "ttnew",
"planPrice": 5675
}
]
}
You need to use SET.
SET pl[1] = :plans
As the docs show here:
https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/Expressions.UpdateExpressions.html#Expressions.UpdateExpressions.SET.AddingListElements
The docs for ADD say
The ADD action supports only number and set data types.
https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/Expressions.UpdateExpressions.html#Expressions.UpdateExpressions.ADD

How do I use "AND" operator with multiple query parameters in nested relation when querying in Prisma?

Its my first time trying prisma and am stuck. So I have "products" and "filters" model.
I want the following query to work. The idea is, I want to fetch the products with dynamic matching query params (name and value). The product query parameters come dynamically from the frontend.
const products = await prisma.product.findMany({
where: {
categoryName,
subCategoryName,
filters: {
some: {
AND: [
{
name: "RAM",
value: "32GB",
},
{
name: "Storage",
value: "1TB",
},
],
},
},
},
include: {
images: true,
},
});
If there's only one parameter, like
{
name:"RAM",
value:"32GB"
}
the query returns appropriate products, but if there are more that one query params (like in the original code above), it returns empty array.
my product schema looks like this, simplified,
name String
filters Filter[]
my filter schema looks like this, simplified
name String
value String?
product Product? #relation(fields: [productId], references:[id])
productId Int?
Thank you very much
I've found the solution here
https://github.com/prisma/prisma/discussions/8216#discussioncomment-992302
It should be like this instead apparently.
await prisma.product.findMany({
where: {
AND: [
{ price: 21.99 },
{ filters: { some: { name: 'ram', value: '8GB' } } },
{ filters: { some: { name: 'storage', value: '256GB' } } },
],
},
})

Paypal window not showing multiple items

I'm creating my own cart and then using Paypal smart button for the payment in Angular.
For multiple items to handle, I'm uing items array in createOrder method at the backend in Express.
function arrayOfItems() {
art_details.forEach((item, index) => {
let sku = item.message;
let currency = priceDetails.collPriceL[index];
let tax = priceDetails.taxAmtL[index];
let quantity = item.quantity;
let items = [
{
name: "Collection",
sku: sku,
description: '' + item.collid,
unit_amount: { currency_code: "CAD", value: "" + currency },
tax: { currency_code: "CAD", value: "" + tax },
quantity: quantity,
},
];
return items;
});
}
I'm now using arrayOfItems() as items in createOrder:
const request = new checkoutNodeJssdk.orders.OrdersCreateRequest();
request.prefer("return=representation");
request.requestBody({
intent: "CAPTURE",
purchase_units: [
{
amount: {
currency_code: "CAD",
value: ...,
breakdown: {
...
},
},
soft_descriptor: orderkey,
items: arrayOfItems(),
shipping: {
...
},
},
],
});
Suppose I'm creating order for 2 items. art_details contains array of items I need to purchase. My order is creating successfully but the Paypal window doesn't show the items in right side. (it should appear as a dropdown of items).
What am I missing here?
Thanks

Sequelize - Select on associated table

My problem:
I am creating an route which will return some informations about a group, it has an id, an user assigned and also has some documents. I just want to show how much documents exists, in SQL would be SELECT COUNT, but how can i do this in this in sequelize?
My code:
async list(req, res){
const docGroups = await DocGroup.findAll({
raw: true,
include: [{
model: User,
as: 'userAssigned'
},
{
model: Document,
as: 'Document'
}
]
}).then(groups => {
const result = groups.map(group => {
return Object.assign(
{},
{
id: group.id,
name: group.name,
userAssinged: group['userAssigned.firstName'],
docAmount: // I want to put documents' count here
}
)
})
console.log(groups)
})
}
What is printed in console.log(groups):
[
{
id: 1,
name: 'pleaseworks',
createdAt: 2020-06-10T02:38:11.531Z,
updatedAt: 2020-06-10T02:38:11.531Z,
'userAssigned.id': 1,
'userAssigned.firstName': 'Please',
'userAssigned.lastName': 'Works',
'userAssigned.email': 'pleaseworks#gmail.com',
'userAssigned.password': '$2a$08$3BA4I4dsaQ3lsHy342344b5P41v5eHWjwqv6dve28nSdqbGvhsdS',
'userAssigned.createdAt': 2020-06-10T02:37:29.062Z,
'userAssigned.updatedAt': 2020-06-10T02:37:29.062Z,
'userAssigned.groupId': null,
'Document.id': 2,
'Document.description': 'deowkdopewkdwe',
'Document.content': 'odepodkewokodwe',
'Document.groupId': 1,
'Document.createdAt': 2020-06-10T02:43:46.005Z,
'Document.updatedAt': 2020-06-10T02:43:46.005Z
}
]
If DocGroup has many Document try something like this:
{
model: Document,
attributes: [[sequelize.fn('COUNT', sequelize.col('id')), 'docAmount']]
as: 'Document'
}

Resources