how to pass param while getting billing data azure function - azure

For getting the azure subscription billing data I am passing params it's not apply
const axios = require('axios');
let usage = [];
function getUsage(subscriptionId, accessToken) {
const url = `https://management.azure.com/subscriptions/${subscriptionId}/providers/Microsoft.Consumption/usageDetails?api-version=2019-01-01`
const options = {
headers: {
Authorization: `Bearer ${accessToken}`
}
}
// I am trying to pass data for filtering
const params ={
type: "Usage",
timeframe: "MonthToDate",
dataset: {
granularity: "None",
aggregation: {
totalCost: {
name: "PreTaxCost",
function: "Sum"
}
},
grouping: [
{
type: "Dimension",
name: "MeterCategory"
},
{
type: "Dimension",
name: "ResourceLocation"
},
{
type: "Dimension",
name: "ResourceGroup"
} ]
}
}
axios.get(url, options, params).then(response => {
console.log('response.data------', response.data);
}).catch(error => {
console.log(error);
});
}
//calling API here
await getUsage(
"subscriptionId",
"access-token"
);

Please change the format of your params from
params ={ type: "Usage", timeframe: "MonthToDate", dataset: { granularity: "None", aggregation: { totalCost: { name: "PreTaxCost", function: "Sum" } }, grouping: [ { type: "Dimension", name: "MeterCategory" }, { type: "Dimension", name: "ResourceLocation" }, { type: "Dimension", name: "ResourceGroup" } ] } }
to
params ={params:{ type: "Usage", timeframe: "MonthToDate", dataset: { granularity: "None", aggregation: { totalCost: { name: "PreTaxCost", function: "Sum" } }, grouping: [ { type: "Dimension", name: "MeterCategory" }, { type: "Dimension", name: "ResourceLocation" }, { type: "Dimension", name: "ResourceGroup" } ] } }}
Just add a "{params:" at the beginning and add a "}" at the end.
I think "params" should be a parameter of it. Please have a try.

Related

Nested object iteration

Fighting with this one for a while now...
I'm trying to modify each image object by adding more keys-values and changing some values.
As the keys are not having the same names, I need to identify the images by .hasOwnProperty('formats')
The object can be even more nested not only with key-values pairs but with arrays as well (this is where it gets complicated)
const object = {
name: "help",
mainImage: {
name: "picture1",
formats: {
small: {
name: "small_picture1",
},
medium: {
name: "medium_picture1",
},
large: {
name: "large_picture1",
},
},
},
carousel: [
{
name: "picture2",
formats: {
small: {
name: "small_picture2",
},
medium: {
name: "medium_picture2",
},
large: {
name: "large_picture2",
},
},
},
{
name: "picture3",
formats: {
small: {
name: "small_picture3",
},
medium: {
name: "medium_picture3",
},
large: {
name: "large_picture3",
},
},
},
],
nestedPage: {
name: "moreHelp",
mainImage: {
name: "picture4",
formats: {
small: {
name: "small_picture4",
},
medium: {
name: "medium_picture4",
},
large: {
name: "large_picture4",
},
},
},
carousel: [
{
name: "picture5",
formats: {
small: {
name: "small_picture5",
},
medium: {
name: "medium_picture5",
},
large: {
name: "large_picture5",
},
},
},
{
name: "picture5",
formats: {
small: {
name: "small_picture5",
},
medium: {
name: "medium_picture5",
},
large: {
name: "large_picture5",
},
},
},
],
},
};
This is what I tried, but it only goes to a certain level.
const customSanitizer = (entity) => {
const isObject = (value) => {
return !!(value && typeof value === "object" && !Array.isArray(value));
};
if (isObject(entity)) {
Object.entries(entity).forEach(([key, value]) => {
if (isObject(entity[key])) {
if (value.hasOwnProperty("formats")) {
entity[key] = formatImageObject(value);
} else {
customSanitizer(entity[key]);
}
} else {
customSanitizer(entity[key]);
}
});
}
if (Array.isArray(entity)) {
entity.forEach((node) => {
customSanitizer(node);
});
}
}

how to update the specific field in mongoose

the present Object is :-
{
_id: "abc12344",
renderId: '123456789',
concernTo: [{
name: 'vijay 4',
id: 'snhdkjn786786',
commons: []
},
{
name: 'ak',
id: 'sdkfg787877',
commons: []
}
]
}
Output needs to be like:
{
_id: "abc12344",
renderId: '123456789',
concernTo: [{
name: 'vijay 4',
id: 'snhdkjn786786',
commons: [{to: "xyz", from:"abc"}, {to: "xyz", from:"abc"}]
},
{
name: 'ak',
id: 'sdkfg787877',
commons: []
}
]
}
So need to push data in concernTo in commons field
In query i'm trying to search by renderId and id in "concernTo" array field and trying to update the object.
Query for that:---
let obj = { to: "xyz", from: "abc" };
let filter = {
renderId: "123456789",
"concernTo.id": "snhdkjn786786",
};
let update = {
$push: {
"concernTo.id.$": { subComment: obj },
},
};
let doc = await blogsCommentModel.findOneAndUpdate(filter, update, {
returnOriginal: false,
});
console.log(doc);
You want to be using arrayFilters for this, like so:
let doc = blogsCommentModel.findOneAndUpdate(filter,
{
"$push": {
"concernTo.$[elem].commons": obj
}
},
{
arrayFilters: [
{
"elem.id": "snhdkjn786786"
}
]
})
Mongo Playground

Displaying specific id from json file with reactjs

How could I display data from a json file using reactjs.
I would like to display a specific value on my website using a json file.
Using this example json file.
const data = [
{
items: {
item: [
{
id: "0001",
type: "donut",
name: "Cake",
ppu: 0.55,
batters: {
batter: [
{
id: "377",
type: "Regular",
},
{
id: "609",
type: "Chocolate",
},
{
id: "788",
type: "Blueberry",
},
{
id: "809",
type: "Devil's Food",
},
],
},
topping: [
{
id: "5001",
type: "None",
},
{
id: "5002",
type: "Glazed",
},
{
id: "5005",
type: "Sugar",
},
{
id: "5007",
type: "Powdered Sugar",
},
{
id: "5006",
type: "Chocolate with Sprinkles",
},
{
id: "5003",
type: "Chocolate",
},
{
id: "5004",
type: "Maple",
},
],
},
],
},
},
];
How could I access for example items.item.batters.batter for id 609 and display the type in this case "Chocolate" using reactjs without using something like this:
batters.batter[1].type
and instead displaying it for the specific id (609)?
If you need to find a specific object, that has a specific value in a list of objects, you can do it as such:
const [batter, setBatter] = useState([
{
id: "377",
type: "Regular"
},
{
id: "609",
type: "Chocolate"
},
{
id: "788",
type: "Blueberry"
},
{
id: "809",
type: "Devil's Food"
}
]);
const [results, setResults] = useState([]);
const searchInList = () => {
let _results = [];
let toSearch = 609;
for (var i = 0; i < batter.length; i++) {
for (key in batter[i]) {
if (batter[i][key].indexOf(toSearch) != -1) {
_results.push(batter[i]);
}
}
}
};
setResults(_results);
useEffect(() => {
searchInList();
}, [batter]);
You can read more about this here: JS search in object values

Group nested fields with aggregation and return results with others fields mongo db

I need to change the structure of some field in my mongoDB document.
Here the sample:
[
{
_id: "ObjectId('997v2ha1cv9b0036fa648zx3')",
title: "Adidas Predator",
size: "8",
colors: [
{
hex: "005FFF",
name: "Blue"
},
{
hex: "FF003A",
name: "Red"
},
{
hex: "FFFE00",
name: "Yellow"
},
{
hex: "07FF00",
name: "Green"
},
],
extras: [
{
description: "laces",
type: "exterior"
},
{
description: "sole",
type: "interior"
},
{
description: "logo"
},
{
description: "stud",
type: "exterior"
}
],
media: {
images: [
{
url: "http://link.com",
type: "exterior"
},
{
url: "http://link3.com",
type: "interior"
},
{
url: "http://link2.com",
type: "interior"
},
{
url: "http://link4.com",
type: "exterior"
}
]
}
}
];
My goal is to group some fields:
colors need to be and array with just the colors,
extras need to be an array with 3 object each one for a "type" (interior, exterior, null)
the same for images that is inside media
Here what I expected:
{
_id: "ObjectId('997b5aa1cv9b0036fa648ab5')",
title: "Adidas Predator",
size: "8",
colors: ["Blue", "Red", "Yellow", "Green"],
extras: [
{type: exterior, description: ["laces", "stud"]},
{type: interior, description: ["sole"]},
{type: null, description: ["logo"]}
],
images: [
{type: exterior, url: ["http://link.com", "http://link4.com"]},
{type: interior, url: ["http://link2.com", "http://link3.com"]},
]
};
With my code I can achieve my goal but I don't understand how to show all the information together through the pipeline.
Here my code:
db.collection.aggregate([
{
$project: {
title: 1,
size: 1,
colors: "$colors.name",
extras: 1,
media: "$media.images"
},
},
{
$unwind: "$media"
},
{
$group: {
_id: {
type: "$media.type",
url: "$media.url",
},
},
},
{
$group: {
_id: "$_id.type",
url: {
$push: "$_id.url"
},
},
},
]);
The result is:
[
{
_id: "exterior",
url: [
"http://link.com",
"http://link4.com"
]
},
{
_id: "interior",
url: [
"http://link3.com",
"http://link2.com"
]
}
];
If I do the same thing with extras I get the same (correct) structure.
How can I show all the data together like in the expected structure?
Thanks in advice.
The strategy will be to maintain the require parent fields throughout the pipeline using $first to just grab the initial value, It ain't pretty but it works:
db.collection.aggregate([
{
"$addFields": {
colors: {
$map: {
input: "$colors",
as: "color",
in: "$$color.name"
}
}
}
},
{
$unwind: "$extras"
},
{
"$addFields": {
imageUrls: {
$map: {
input: {
$filter: {
input: "$media.images",
as: "image",
cond: {
$eq: [
"$$image.type",
"$extras.type"
]
}
}
},
as: "image",
in: "$$image.url"
}
}
}
},
{
$group: {
_id: {
_id: "$_id",
extraType: "$extras.type"
},
extraDescriptions: {
"$addToSet": "$extras.description"
},
imageUrls: {
"$first": "$imageUrls"
},
colors: {
$first: "$colors"
},
size: {
$first: "$size"
},
title: {
$first: "$title"
}
}
},
{
$group: {
_id: "$_id._id",
colors: {
$first: "$colors"
},
size: {
$first: "$size"
},
title: {
$first: "$title"
},
images: {
$push: {
type: {
"$ifNull": [
"$_id.extraType",
null
]
},
url: "$imageUrls"
}
},
extras: {
$push: {
type: {
"$ifNull": [
"$_id.extraType",
null
]
},
description: "$extraDescriptions"
}
}
}
}
])
Mongo Playground
You can try $function operator, to defines a custom aggregation function or expression in JavaScript.
$project to show required fields and get array of colors name
$function, write your JS logic if you needed you can sort this logic of group, it will return result with 2 fields (extras, images)
$project to show required fields and separate extras and images field from result
db.collection.aggregate([
{
$project: {
title: 1,
size: 1,
colors: "$colors.name",
result: {
$function: {
body: function(extras, images) {
function groupBy(objectArray, k, v) {
var results = [], res = objectArray.reduce((acc, obj) => {
if (!acc[obj[k]]) acc[obj[k]] = [];
acc[obj[k]].push(obj[v]);
return acc;
}, {});
for (var o in res) {
results.push({ [k]: o === 'undefined' ? null : o, [v]: res[o] })
}
return results;
}
return {
extras: groupBy(extras, 'type', 'description'),
images: groupBy(images, 'type', 'url')
}
},
args: ["$extras", "$media.images"],
lang: "js"
}
}
}
},
{
$project: {
title: 1,
size: 1,
colors: 1,
extras: "$result.extras",
images: "$result.images"
}
}
])
Playground
IMPORTANT:
Executing JavaScript inside an aggregation expression may decrease performance. Only use the $function operator if the provided pipeline operators cannot fulfill your application's needs.

How to aggregate grouping with filtered array and filtered sum?

I'm trying to get my head around this aggregation framework, and I'm kind of stuck, I would love some help.
So I have a collection of events, that simplified and already filtered look something similar to this:
{ creation: 54233, eventName: "elapsedTime", userId: 1, url: "/thing/53e245ca", data: { number: 5 } },
{ creation: 64033, eventName: "elapsedTime", userId: 1, url: "/thing/53e245ca", data: { number: 3 } },
{ creation: 50298, eventName: "elapsedTime", userId: 1, url: "/thing/53e245ca", data: { number: 2 } },
{ creation: 74220, eventName: "toggle", userId: 1, url: "/thing/53e245ca", data: { status: true } },
{ creation: 84233, eventName: "elapsedTime", userId: 2, url: "/thing/190345a9", data: { number: 8 } },
{ creation: 59511, eventName: "elapsedTime", userId: 2, url: "/thing/190345a9", data: { number: 10 } },
{ creation: 14236, eventName: "toggle", userId: 2, url: "/thing/190345a9", data: { status: false } },
{ creation: 80637, eventName: "toggle", userId: 2, url: "/thing/cc2b8b91", data: { status: true } },
{ creation: 99239, eventName: "toggle", userId: 2, url: "/thing/cc2b8b91", data: { status: false } }
And I want them to be aggregated like this:
{
userId: 1,
toggles: [
{ creation: 74220, url: "/thing/53e245ca", data: { status: true } }
],
elapsedSum: 10
},
{
userId: 2,
toggles: [
{ creation: 14236, url: "/thing/190345a9", data: { status: false } },
{ creation: 80637, url: "/thing/cc2b8b91", data: { status: true } },
{ creation: 99239, url: "/thing/cc2b8b91", data: { status: false } },
],
elapsedSum: 18
}
So I basically want to group by user, have the sum of all elapsedTime for each user, and have an array of all the toggle events for each user.
db.getCollection('heya').aggregate([
{
"$group": {
"_id": "$userId",
"toogles": {
"$addToSet": {
"$cond": {
"if": {
"$eq": [
"$eventName",
"toggle"
]
},
"then": {
"creation": "$creation",
"url": "$url",
"data": "$data"
},
"else": null
}
}
},
"elapsedSum": {
"$sum": {
"$cond": {
"if": {
"$eq": [
"$eventName",
"elapsedTime"
]
},
"then": "$data.number",
"else": 0
}
}
}
}
}
])
You may replace null from the array or unwind it to get the required result

Resources