value.getTime is not a function GraphQL custom scalar Date - javascript

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
}

Related

Express-validator: How can i use date birthday validator with checkschema?

I'm developing a project with a form and I need use a validator. I choice express-validator to this job. I am using express-validator with checkschema format and I can't to validate the date. The format date is yyyy/mm/dd. I've tried the code below:
`export const validator = {
editAction: checkSchema({
date: {
isISO8601: {
errorMessage: `date of birth is not a valid iso date`
},
isBefore: {
date: '01-01-2008',
errorMessage: 'should be less than 01-01-2008'
},
isAfter: {
date: '01-01-1920',
errorMessage: 'should be less than 01-01-1920'
}
},
}),
};`
I never used this library. Help me please, how can i get the right validator schema?
Try this,
export const validator = {
editAction: checkSchema({
date: {
custom: {
options: (value, { req }) => {
const dateFormat = /^\d{4}\/\d{2}\/\d{2}$/;
if (!dateFormat.test(value)) {
throw new Error("Invalid date format. Use yyyy/mm/dd");
}
return true;
}
}
}
})
};
Note that you have to import checkSchema from express-validator first.

How can I disable an button/div for a certain amount of time, while using getTime() logic from the database, using React/Node.js

I want to disable a div for a certain period of time. Im trying the whole day to make this work, but somehow I am stuck. I don't want to use some front end logic like setTimeout() and add/remove classes or disable pointer-event. The logic I am trying to implement is to share a key with the current time when the document was posted to the database timeCreateInMS: { default: new Date().getTime(), in miliseconds and when I try to press the button once more to share I'll should first get all the documents from the mongo db, filter them and find all the documents that have been posted on the DB within the last 5 minutes with this kind of logic const filteredArray = array.filter((a) => {a.timeCreateInMS > new Date().getTime() - 300000}), but for some reason it doeasn't work, either I misunderstood how getTime() works or I made a major error somewhere along the line. Here is the important code used.
Getting the Data from the DB on the backend
export const getLocations = async (req, res) => {
try {
const locations = await shareLocation.find({});
res.status(200).json(locations);
} catch (error) {
console.log(error);
res.status(409).json("Unable to fetch Locations");
}
};
The schema I am using for the MongoDB
import mongoose from "mongoose";
const locationSchema = mongoose.Schema({
timeShared: {
type: String,
required: true,
},
dateShared: {
type: String,
required: true,
},
latitude: {
type: String,
required: true,
},
longitude: {
type: String,
required: true,
},
city: {
type: String,
},
road: {
type: String,
},
created_at: {
type: Date,
},
timeCreateInMS: {
type: String,
default: new Date().getTime(),
},
});
locationSchema.index({ created_at: 1 }, { expires: 10800 });
export default mongoose.model("shareLocation", locationSchema);
and the frontend logic using react
import styles from "./ShareButton.module.css";
import { useState, useContext, useRef, useEffect, useCallback } from "react";
import ShareIcon from "./ShareIcon";
import DataContext from "../context/DataContext";
import axios from "axios";
function ShareButton() {
const [fetchedLocations, setFetchedLocations] = useState([]);
const [filterShared, setFilterShared] = useState([]);
const [dateRN, setDateRN] = useState(new Date().getTime());
const { createLocation } = useContext(DataContext);
const getLocations = useCallback(async (setFetch) => {
const { data } = await axios.get("http://localhost:5000/radar");
setFetch(data);
}, []);
const submitLocationHandler = async () => {
if (filterShared.length <= 0) {
createLocation();
setDateRN(new Date().getTime());
} else {
console.log(
"Already Shared in the last 5 mintues"
);
}
};
useEffect(() => {
getLocations(setFetchedLocations);
}, [getLocations]);
useEffect(() => {
setDateRN(new Date().getTime());
setFilterShared(
fetchedLocations.filter(
(location) => parseInt(location.timeCreateInMS) > parseInt(dateRN) - 300000
)
);
}, [fetchedLocations]);
const onClickHandler = () => {
submitLocationHandler();
getLocations(fetchedLocations);
};
return (
<div className={styles.share_button_container}>
<div onClick={onClickHandler} }>
</div>
</div>
);
}
export default ShareButton;
p.s the createLocation is taken from another document from the Context API, not important in this scenario, works as expected.
I cannot wrap my head around, why this doesn't work, from what I am trying to achieve is when posting once, there should be a timeout for 5 minutes and once the time passes the user should be able to post once more, but for some reason, the document that was posted in the last 5 min is not filtered in the logic above.
Anyone has an idea where I made the error, or has any better way to disable the component for a certain amount of time, getting the information from the database if possible, so the logic wont be interrupted when frontend or backend server is down for some sec, I thought the best way is to make the condition from the DB itself

How to convert object timestamp to firebase timestamp?

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'
}

property missing in returned json response / javascript

Im working in React on some weather widget which displays temp and rain forecast. Im fetching data from OpenWeather and my json response looks like:
//rainy day
0:{
main: {
temp:10}
rain: {
3h: 1000}
}
//sunny day
1:{
main: {
temp:10}
}
the problem is rain.3h property appears in returned response only when it has some data, otherwise its missing. My request looks like:
async getForecast(term) {
const forecastUrl = "http://api.openweathermap.org/data/2.5/forecast?q=" + term + "&appid=" + apiKey + "&lang=us&units=metric&cnt=16";
try {
let response = await fetch(forecastUrl);
if (response.ok) {
let jsonResponse = await response.json();
let forecast = jsonResponse.list.map(
day => {
return {
temp: day.main.temp,
rain: day.rain["3h"], // can't map missed property
}
}
)
return (forecast);
}
} catch (error) {
console.log(error);
}
}
And Im getting error
TypeError: Cannot read property '3h' of undefined.
How may I add default rain:0 when the property is missing from response
You could do a check using ternary operator
let forecast = jsonResponse.list.map(
day => {
return {
temp: day.main.temp,
rain: day.rain?day.rain["3h"] : ''
}
}
)
You should check whether the property exists or not
var obj = {};
obj.temp = day.main.temp;
if (day.hasOwnProperty("rain") && day.rain.hasOwnProperty("3h"))
obj.rain = day.rain["3h"];
return obj;
You can use assignment with double ampersand "&&":
let forecast = jsonResponse.list.map(
day => {
return {
temp: day.main.temp,
rain: day.rain && day.rain["3h"] || 0
}
}
)
This works because if day.rain is undefined then the second part of the boolean expression will not be evaluated, avoiding the cannot read property of undefined error, and the value from the OR will be used for default assignment.

node red function and export to CSV

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

Categories