I have below request body,
const requestbody = {
"applicationname":"app1",
"applicationtype":"permenant",
"startDate":"24 march",
"endDate":"30 march",
"refreshtime":""
}
I need to send "startDate" and "endDate" to backend only if its value is nonempty like
const requestbody = {
"applicationname":"app1",
"applicationtype":"permenant",
"startDate":"24 march",
"endDate":"30 march",
"refreshtime":"",
}
else request body should be
const requestbodywithoutdate = {
"applicationname":"app1",
"applicationtype":"permenant",
"refreshtime":30
}
The easiest way is doing something like:
const requestbody = {
"applicationname":"app1",
"applicationtype":"permenant",
...(startDate ? { startDate } : {}),
...(endDate ? { endDate } : {}),
"endDate":"30 march",
"refreshtime":"",
}
Assuming startDate is a string containing 24 march and endDate a string containing 30 march.
I used here a string as boolean, but it's up to you to replace startDate ? by somthing like values.startDate ? or other condition resulting to a boolean.
You can use lodash to exclude it.
const requestBody = _.omitBy(myObject, _.isNil)
Related
I want to convert the following timestamp:
Object {
"_nanoseconds": 725000000,
"_seconds": 1621386976,
}
to this timestamp:
t {
"nanoseconds": 725000000,
"seconds": 1621386976,
}
How can I go about doing this? I am stumped. I have tried toDate() and variations of this, but nothing is working.
Found this on reddit:
getTimeText = (timeObject: any) => {
// Convert to time text once it's of type firestore.Timestamp
const getTextFromTimestamp = (timestamp: app.firestore.Timestamp) => {
return this.timeAgo.format(timestamp.toDate())
}
if (timeObject instanceof app.firestore.Timestamp) {
// Check if Timestamp (accessed from client SDK)
return getTextFromTimestamp(timeObject)
} else if (Object.prototype.toString.call(timeObject) === '[object Object]') {
// Check if it's a Map (accessed from Cloud Functions)
const seconds = timeObject['_seconds']
const nanoseconds = timeObject['_nanoseconds']
if (seconds && nanoseconds) {
const timestamp = new app.firestore.Timestamp(seconds, nanoseconds)
return getTextFromTimestamp(timestamp)
}
}
console.log('Couldn\'t parse time', timeObject)
// Fallback
return 'some time ago'
}
i try to query find by month in mongodb,
my data in Daq collection is like this:
"
_id" : ObjectId("5f14081c14c08a261b816d57"),
"battery_voltage" : 3673,
"total_usage" : 0.483,
"signal" : 14,
"samplehour" : "2020-07-18T23:59:59-04:00",
"sampledate" : "2020-07-18T23:59:59-04:00",
this is my queries:
let n = moment().month()
let test = await Daq.aggregate([
{$addFields: { "month" : {$month: '$sampledate'}}},
{$match: { month: n}}
]);
i already try this too :
let n = moment().month()
let test = await Daq.aggregate([
{$project: { "month" : {$month: '$sampledate'}}},
{$match: { month: n}}
]);
but the result is always
"message": "can't convert from BSON type string to Date"
how you guys can solve this?
Your sampledate is not saved as a date object but rather as a string. You first need to convert it to a date and then you can use functions such as $month.
$addFields: {
"month": {
$month: {
$toDate: "$sampledate"
}
}
}
https://mongoplayground.net/p/XOdfYtEXqLc
I assume the fact that it's a string is actually a bug in your insert code and you should probably fix that instead.
I receive LASTUPDATE: 1579452599 response from an external API,
I want to parse the value in this format: Mon Jan 19 2020 13:44:04, I tried using custom scallar, but I'm having this error:
value.getTime is not a function
What am I doing wrong?
This is my code,
resolvers.js
import fetch from 'node-fetch';
import { GraphQLScalarType } from 'graphql';
import { Kind } from 'graphql/language';
export const resolvers = {
Query: {
getCrypto: async() => {
const response = await fetch('https://min-api.cryptocompare.com/data/top/totalvolfull?limit=10&tsym=USD&api_key=260d15e639be7b967c2b0e4f9f3b6d656897ccbdfe772b1d24818d9f96d3a6ed')
let data = await response.json()
return data.Data[0].RAW.USD;
}
},
Date: new GraphQLScalarType({
name: 'Date',
description: 'Date custom scalar type',
parseValue(value) {
return new Date(value); // value from the client
},
serialize(value) {
console.log(value)
return value.getTime(); // value sent to the client
},
parseLiteral(ast) {
if (ast.kind === Kind.INT) {
return parseInt(ast.value, 10); // ast value is always in string format
}
return null;
},
})
};
schema.graphql
type CryptoCurrency {
FROMSYMBOL: String
PRICE: Float
TOSYMBOL: String
LASTUPDATE: Date
}
type Query {
getCrypto: CryptoCurrency
}
scalar Date
type MyType {
created: Date
}
In console I see the value
In case anyone else comes here from a google search for a similar issue
You should convert LASTUPDATE from timestamp to actual date, and have to multiply by 1000 because Javascript uses milliseconds.
serialize(value) {
console.log( new Date(value).toISOString())
return new Date(value * 1000).toISOString(); // value sent to the client
}
I am trying to sort an Array using a String field and it is sorting it wrongly.
My code looks like this.
let tempWEArray = [
{
"from" : "09/2005",
"to" : "11/2006"
},
{
"from" : "09/2006",
"to" : "11/2007"
},
{
"from" : "12/2007",
"to" : "01/2009"
},
{
"from" : "01/2009",
"to" : "12/2012"
},
{
"from" : "01/2013",
"to" : "03/2018"
}]
function sortBy(prop){
return function(a,b){
if( a[prop] < b[prop])
{
return -1;
}
else if( a[prop] > b[prop] )
{
return 1;
}
return 0;
}
}
console.log(tempWEArray.sort(sortBy("to")))
The output obtained is like below.
0: Object { from: "12/2007", to: "01/2009" }
1: Object { from: "01/2013", to: "03/2018" }
2: Object { from: "09/2005", to: "11/2006" }
3: Object { from: "09/2006", to: "11/2007" }
4: Object { from: "01/2009", to: "12/2012" }
The Array isn't getting sorted properly as you can see above. One field is misplaced. Am i doing something wrong?
All the below answers work, I've selected the Answer which I have implemented. Thanks everyone.
You could first parse those dates and then you can use - to sort them.
let arr = [{"from":"09/2005","to":"11/2006"},{"from":"09/2006","to":"11/2007"},{"from":"12/2007","to":"01/2009"},{"from":"01/2009","to":"12/2012"},{"from":"01/2013","to":"03/2018"}]
const parse = str => {
let date = new Date;
let [month, year] = str.split('/')
date.setYear(year);
date.setMonth(+month - 1)
return date;
}
const sortBy = prop => (a, b) => {
return parse(b[prop]) - parse(a[prop])
}
arr.sort(sortBy('to'))
console.log(arr)
Convert it to a date in your sort and it'll work as you intended.
seperate each component of the date string and reverse it
const dateArray = b[prop].split("/").reverse()
Use the spread operator to create a timestamp with Date.UTC and then use new Date to create a date.
new Date(Date.UTC(...dateArray))
Then use the - between two dates to find which one is bigger in a sort function.
Some example:
const res = new Date(Date.UTC(..."11/2006".split("/").reverse()))
console.log(res);
Full solution:
let tempWEArray = [{"from":"09/2005","to":"11/2006"},{"from":"09/2006","to":"11/2007"},{"from":"12/2007","to": "01/2009"},{"from":"01/2009","to": "12/2012"},{"from":"01/2013","to": "03/2018"}]
function sortBy(prop) {
return function(a, b) {
const dateArr1 = a[prop].split("/").reverse();
const dateArr2 = b[prop].split("/").reverse();
//make sure months are between 0 and 11
//can be skipped if this is already ensured.
dateArr1[1]--;
dateArr2[1]--;
return new Date(Date.UTC(...dateArr2)) - new Date(Date.UTC(...dateArr1));
}
}
console.log(tempWEArray.sort(sortBy("to")))
You can use moment.js for date camparation. example:
let tempWEArray = [
{
"from" : "09/2005",
"to" : "11/2006"
},
{
"from" : "09/2006",
"to" : "11/2007"
},
{
"from" : "12/2007",
"to" : "01/2009"
},
{
"from" : "01/2009",
"to" : "12/2012"
},
{
"from" : "01/2013",
"to" : "03/2018"
}];
const sortedArray = tempWEArray.sort(
(first, second) => moment(first.to, 'MM/YYYY')
.isSameOrAfter(moment(second.to, 'MM/YYYY')));
console.log(sortedArray);
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.23.0/moment.min.js"></script>
function sortBy(prop) {
return function(a, b) {
const dateArray = b[prop].split("/").reverse()
console.log()
}
}
You could replace the date pattern with a comparable string and omit if the string has not a date pattern.
function sortBy(prop){
return function(a,b){
var valueA = a[prop].replace(/^(\d{2})\/(\d{4})$/, '$2-$1'),
valueB = b[prop].replace(/^(\d{2})\/(\d{4})$/, '$2-$1');
return valueA.localeCompare(valueB);
}
}
var tempWEArray = [{ from: "09/2005", to: "11/2006" }, { from: "09/2006", to: "11/2007" }, { from: "12/2007", to: "01/2009" }, { from: "01/2009", to: "12/2012" }, { from: "01/2013", to: "03/2018" }]
console.log(tempWEArray.sort(sortBy("to")))
.as-console-wrapper { max-height: 100% !important; top: 0; }
I have the raspberry pi and sense hat. I wish to extract acceleration z,y,x,Temperature and Pressure and time to csv. However, the code I've written does not do what i want it to do. I was expecting the data to leave the function in an array but the debug window shows them as separate objects. How do i get acceleration z,y,x and time to leave as one array so i can export to CSV?
29/03/2017, 17:17:23node: abf1ef08.31a6f
msg : Object
object
payload: 0.9487
_msgid: "ae0db049.020f6"
29/03/2017, 17:17:23node: abf1ef08.31a6f
msg : Object
object
payload: 0.2781
_msgid: "ae0db049.020f6"
29/03/2017, 17:17:23node: abf1ef08.31a6f
msg : Object
object
payload: 0.1491
_msgid: "ae0db049.020f6"
29/03/2017, 17:17:23node: abf1ef08.31a6f
msg : Date
"Wed Mar 29 2017 16:17:25 GMT+0000 (UTC)
Here's the function code :
var msgAccelZ,msgAccelX,msgAccelY,msgTemperature,msgPressure,msgCurrentTime;
if (msg.topic === 'motion') {
msgAccelZ = { payload: msg.payload.acceleration.z, };
msgAccelX = { payload: msg.payload.acceleration.x, };
msgAccelY = { payload: msg.payload.acceleration.y, };
} else if (msg.topic === 'environment') {
msgTemperature = { payload: msg.payload.temperature };
msgPressure = { payload: msg.payload.pressure };
}
msgCurrentTime = new Date();
return [ [msgAccelZ, msgAccelX, msgAccelY,msgCurrentTime] ,[msgTemperature, msgPressure, msgCurrentTime] ];
A Function needs to return a message object, not just a raw value.
By convention, you'd put the data you want to return under msg.payload:
msg.payload = [ [msgAccelZ, msgAccelX, msgAccelY,msgCurrentTime] ,[msgTemperature, msgPressure, msgCurrentTime] ];
return msg;
The documentation for the Function node explains in more detail: http://nodered.org/docs/writing-functions