Count unseen messages from object Lodash - node.js

I am trying to get count of unseen messages from object in lodash.
below is my object
[
"conversation_id": "5a88779b2321141f2864e484"
"messages": [
{
"message_id": "5a88779b2321141f2864e483",
"sender_uid": 2,
"receiver_uid": 1,
"created": "2018-02-17T18:42:35.252Z",
"status": 1,
"delivered": false,
"seen": true,
}
]
]
I want to get count of seen: false messages

You can use filter to get all see = false messages and then can check length
var users = {
"conversation_id": "5a88779b2321141f2864e484",
"messages": [
{ "message_id": "5a88779b2321141f2864e483","sender_uid": 2,"receiver_uid": 1,"created": "2018-02-17T18:42:35.252Z","status": 1,"delivered": false,"seen": true,},
{ "message_id": "5a88779b2321141f2864e483","sender_uid": 2,"receiver_uid": 1,"created": "2018-02-17T18:42:35.252Z","status": 1,"delivered": false,"seen": false },
{ "message_id": "5b88779b2321141f2864e483","sender_uid": 2, "receiver_uid": 1, "created": "2018-02-17T18:42:35.252Z", "status": 1,"delivered": false,"seen": false,}
]
}
var unseen_messages = _.filter(users.messages, message => { return !message.seen; }).length;
console.log(unseen_messages);
<script src="https://cdn.jsdelivr.net/lodash/4.13.1/lodash.min.js"></script>
Without lodash you can use reduce
var users = {
"conversation_id": "5a88779b2321141f2864e484",
"messages": [
{ "message_id": "5a88779b2321141f2864e483","sender_uid": 2,"receiver_uid": 1,"created": "2018-02-17T18:42:35.252Z","status": 1,"delivered": false,"seen": true,},
{ "message_id": "5a88779b2321141f2864e483","sender_uid": 2,"receiver_uid": 1,"created": "2018-02-17T18:42:35.252Z","status": 1,"delivered": false,"seen": false },
{ "message_id": "5b88779b2321141f2864e483","sender_uid": 2, "receiver_uid": 1, "created": "2018-02-17T18:42:35.252Z", "status": 1,"delivered": false,"seen": false,}
]
}
items = users.messages;
var totalCount = items.reduce((total, obj) => { return (!obj.seen) ? (total +1) : total }, 0);
console.log(totalCount);

_.sumBy would do the trick
const unseenMessages = _.sumBy(users.messages, message => message.seen === false);

Related

Unable to retrive ordered job list from Google Transcoder API

i'm using the node.js client library of google transcoder api. I'm able to retrive a paginated list of some jobs, but i'm not able to order elements by start date. Here my codes:
const { TranscoderServiceClient } = require('#google-cloud/video-transcoder').v1;
class TranscoderApiController {
constructor() {
this.projectId = process.env.GOOGLE_CLOUD_PROJECT;
this.location = process.env.TASK_LOCATION;
}
async getEntries(req, res, next) {
const params = {
pageSize: req.query.pageSize ? parseInt(req.query.pageSize) : 10,
pageToken: req.query.pageToken,
filter: req.query.filter,
orderBy: req.query.orderBy
}
const client = new TranscoderServiceClient();
const result = await client.listJobs({
parent: client.locationPath(this.projectId, this.location),
pageSize: params.pageSize,
orderBy: 'createTime.seconds'
}, {
autoPaginate: false
});
if (result.length == 3 && result[2] != undefined) {
return result[2];
} else {
return result[1];
}
}
}
module.exports = new TranscoderApiController();
When i call the getEntries method i receive the following error:
"3 INVALID_ARGUMENT: The request was invalid: sort order \"createTime.seconds\" is unsupported"
If i remove the orderBy: 'createTime.seconds' line then the api works but is not ordered as i want. The result is something like that (i abbreviate the json):
{
"jobs": [
{
"labels": {},
"name": "projects/<id>/locations/europe-west1/jobs/<uuid>",
"inputUri": "",
"outputUri": "",
"state": "SUCCEEDED",
"createTime": {
"seconds": "1656602896",
"nanos": 386772728
},
"startTime": {
"seconds": "1656602900",
"nanos": 755000000
},
"endTime": {
"seconds": "1656603062",
"nanos": 428000000
},
"ttlAfterCompletionDays": 30,
"error": null,
"config": {
"inputs": [
{
"key": "input0",
"uri": "gs://<url>/render_md.mp4",
"preprocessingConfig": null
}
],
"editList": [...],
"elementaryStreams": [...],
"muxStreams": [...],
"manifests": [],
"adBreaks": [],
"spriteSheets": [],
"overlays": [],
"output": {
"uri": "gs://<url>/md.mp4/"
},
"pubsubDestination": {
"topic": "projects/<id>/topics/transcoder_api"
}
},
"jobConfig": "config"
},
...
],
"unreachable": [],
"nextPageToken": "Co8BCjgKDGV1cm9wZS13ZXN0MRIZdHJhbnNjb2Rlci5nb29nbGVhcGlzLmNvbRgBII..."
}
As you can see each job have the startTime.seconds property. I follow the syntax described here:
https://google.aip.dev/132#ordering
Any support to solve the ordered issue is appreciated.

Dynamodb scan on array of objects Filter Expression

I want to scan dynamodb using filter on product_id showing in below json of table.
Can anybody explain how to do scanning using filter of product_id.
Wants to scan dynamodb table data using documentclient.
Wants to find all fields which has product_id: something
{
"mandi_id": 1,
"product": [
{
"updated_price": 24,
"product_id": 2,
"last_price": 23
},
{
"updated_price": 24,
"product_id": 5,
"last_price": 23
}
],
"status": "active",
"createdAt": "2022-04-21T08:23:41.774Z",
"mandiCloseTime": "4pm",
"mandi_description": "anaj mandi",
"mandi_name": "gaziabad anaj mandi",
"state": "uttar pradesh",
"city": "gaziabad",
"main_image_s3": "",
"mandi_latlong": {
"lng": 77.48325609999999,
"lat": 28.680346
},
"mandiOpenTime": "10am",
"updatedAt": "2022-04-21T08:23:41.774Z",
"address_name": "gavindpuram",
"landmark_name": "mandi",
"village": "gaziabad",
"postal": "201013"
}
I have tried the following set of code but it is returning empty array list
var params = {
TableName: "dev-agrowave-mandi-management",
// Select: "ALL_ATTRIBUTES"
FilterExpression: "contains(#product,:product)",
ExpressionAttributeNames: {
"#product": "product",
},
ExpressionAttributeValues: { ":product": {"product_id":parseInt(id)}
}
};
let lastEvaluatedKey = 'dummy'; // string must not be empty
const itemsAll = [];
while (lastEvaluatedKey) {
const data = await docClient.scan(params).promise();
itemsAll.push(...data.Items);
lastEvaluatedKey = data.LastEvaluatedKey;
if (lastEvaluatedKey) {
params['ExclusiveStartKey'] = lastEvaluatedKey;
}
}
return {msg:itemsAll,params:params};

Can you 'filter' the columns from a second leftJoinAndMapOne?

Can the columns of a second leftJoinAndMapOne() be 'filtered' so that it only returns the columns or values that I need inside the object?
Query Builder:
const favorites = await this.favoritesRepo.createQueryBuilder('favorite')
.where('favorite.user_id = :token', { token })
.leftJoinAndMapOne('favorite.item', 'favorite.item_id', 'items')
.select(['favorite.id'])
.addSelect([
'items.title',
'items.description',
'items.price',
'items.stock',
])
.leftJoinAndMapOne(
'items.photos',
PhotosEntity,
'photos',
'favorite.item_id = photos.subject_id and photos.subject_type = :item',
{item: 'item'}
)
return paginate<Favorite>(favorites, options)
Output (GET):
//...
{
"id": 32,
"item": {
"title": "Foo",
"description": "Buzz",
"price": 250.99,
"stock": 10,
"photos": {
"id": 2,
"createdAt": "2021-12-04T04:55:02.408Z",
"url": "https://images.unsplash.com/photo-1633114128729-0a8dc13406b9?ixlib=rb-1.2.1&ixid=MnwxMjA3fDF8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=870&q=80",
"width": 324,
"height": 281,
"size": 42,
"entityId": 18,
"entityType": "item",
"redirectUrl": "https://facebook.com/"
}
}
},
//...
Expected Output:
//...
{
"id": 32,
"item": {
"title": "Foo",
"description": "Buzz",
"price": 250.99,
"stock": 10,
"photos": {
"url": "https://images.unsplash.com/photo-1633114128729-0a8dc13406b9?ixlib=rb-1.2.1&ixid=MnwxMjA3fDF8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=870&q=80"
}
}
},
//...
Any suggestions or changes that I should make to make the output as expected? ๐Ÿค”
.leftJoinAndMapOne(
'items.image',
PhotosEntity,
'photos',
'favorite.item_id = photos.subject_id and photos.subject_type = :item',
{item: 'item'}
)
.addSelect('photos.url')
I tried with .select () or .addSelect () but it doesn't filter columns from photos.
I already resolved it
Query Builder:
const favorites = await this.favoritesRepo.createQueryBuilder('favorite')
.where('favorite.user_id = :token', { token })
.leftJoinAndMapOne('favorite.item', 'favorite.item_id', 'items')
.leftJoinAndMapOne(
'items.photos',
PhotosEntity,
'photos',
'favorite.item_id = photos.subject_id and photos.subject_type = :item',
{item: 'item'}
)
.select(['favorite.id'])
.addSelect([
'items.title',
'items.description',
'items.price',
'items.stock',
'photos.url',
])

Traversing array and changing object values

I'm trying to update the values โ€‹โ€‹of my payments array objects
{
"balance": 109610,
"gifts": [],
"orders": [],
"payments": [{
"isPaid": 0,
"status": "Pending",
"address": "3KsdQbmADyz1KNN7qqX1yZcMXBbfFCm31r",
"date": 1624057559970
}, {
"isPaid": 0,
"status": "Pending",
"address": "3FYQK6YiAaL8fEbDWaXYw38CJN3K2y5dPD",
"date": 1624058531601
}],
"isVendedor": false,
"isAdmin": true,
"createdAt": {
"$date": "2021-06-17T21:10:15.020Z"
},
"username": "teste",
"email": "teste#teste.com",
"password": "$2a$10$qUNkorDuvbf.AYLTvjNc4ebKyNgLa7L9NoTBwAIV8.BfN51umaD9O",
"__v": 3
}
First, I look for the object of the user who made a request to my server
const userPayment = await User.find({"payments.address": notification.address}).exec();
Then I go through the user object and find it until I find the position where I find notification.address again
userPayment.forEach((AllPayments, index) => {
AllPayments.payments.forEach((payment, index) => {
if (payment.address == notification.address) {
if (payment.isPaid || payment.status != "Pending")
return res.json({
success: false,
error: "Payment Already Processed!",
});
const valueToDeposit = Math.round(notification.fiat_amount);
console.log(
userPayment[0].payments[index].isPaid,
userPayment[0].payments[index].status
);
// Set payments[index].isPaid = true
// Set payments[index].status = "Paid"
});
});
So I tried to make these 3 ways and none of them was successful.
userPayment[0].balance += valueToDeposit; // this works when save() is triggered
userPayment[0].payments[index].isPaid = 1; // this doesnt works when save() is triggered
userPayment[0].payments[index].status = "Paid"; // this doesnt works when save() is triggered
userPayment[0].updateOne({"payments.address": notification.address}, { $set: { "payments.$.isPaid": 1,"payments.$.status":"Paid" } },(err, result) => { console.log(err, result); }); this doesnt works
userPayment[0].save()

Mvc5 getting data list from controller to ajax function c#

i am getting data list from controller to ajax function to my datatable.all works well but my question is, I want to get one of list property to textbox and other values to datatable columns.for example:
list= TotalAMount,PAidAmount,RemAmount
and datatable
Totalamount| PaidAMount | RemAmount| ---------??
20 | 4 | 16 |
so this works fine but i want to get TotalAmount value to some textbox also like textbox=20.
my JS function==>>
`
function AddGetHistoryView(SupplierID) {
$('#HistoryModal').modal('show');
Datatabless = $("#HistoryTable").DataTable({
"autoWidth": false,
"ajax": {
"type": "GET",
"url": "#Url.Action("getHistoryData", "Supplier")/" + SupplierID,
"datatype": "JSON",
data: {
"Amount": $("#TotalAmount").val()
},
data: { SupplierID: SupplierID },
},
"columns": [
{
"data": "DetailID",
"visible": false,
},
{
"data": "TotalAmount",
"width": "5%",
},
{
"data": "PaidAmount",
"width": "5%",
},
{
"data": "RemAmount",
"width": "5%",
},
{
"data": "PaidDate",
"width": "5%",
},
{
"data": "PaymentType",
"width": "5%",
},
{
"data": "DetailID", "render": function (data) {
return "<a class='btn btn-success' onclick=EditRow(" + data + ") style='margin-left:12px'><i class='glyphicon glyphicon-edit'> Update</i><a/>,<a class='btn btn-danger' onclick=deleteRow(" + data + ") style='margin-left:12px'><i class='glyphicon glyphicon-trash'> Delete</i> <a/>";
},
"width": "40%",
"orderable": false,
"pagingType": "full_numbers",
"paging": true,
},
],
});
}
`
Controller Method==>
public ActionResult getHistoryData(int SupplierID)
{
ob.Configuration.ProxyCreationEnabled = false;
var data = ob.Table_Supplier.Join(ob.Table_SupplierDetails, sup => sup.SupplierID, det => det.SupplierID, (sup, det) => new
{
DetailID=det.DetailID,
SupplierID = sup.SupplierID,
TotalAmount = det.TotalAmount,
RemAmount = det.RemAmount,
PaidAmount = det.PaidAmount,
PaidDate = det.PaidDate,
PaymentType = det.PaymentType,
Amount = sup.Amount
}).Where(x=>x.SupplierID==SupplierID).ToList();
return Json(new { data = data }, JsonRequestBehavior.AllowGet);
}

Resources