Reputation: 17
I have a nodejs project and I need to store the response data of this axios request
let px2resp;
async function sendPx2() {
try {
let data = await axios.post('https://collector-pxajdckzhd.px-cloud.net/api/v2/collector', qs.stringify(PX2data), {
headers: PX2headers
});
px2resp = data;
return px2resp;
} catch (e) {
return e;
}
}
the way that I'm doing it right now is
let testing = async () => {
var a = await sendPx2();
console.log(a)
}
testing();
But the issue with this is that it makes the request everytime I want to use the data which is no ideal. Is there anyway for me to store this response data and use it without having to make the request multiple times?
Upvotes: 0
Views: 664
Reputation: 117
(Assuming you don't want to store data in a file)
This may be the approach you are looking for:
let px2resp;
let alreadyFetched = false;
let cachedData = null;
async function sendPx2() {
// check if data was fetch already (to avoid same request multiple times)
// if so, return previous fetched data
if (alreadyFetched) return cachedData;
// else fetch data
let data = await axios.post(
'https://collector-pxajdckzhd.px-cloud.net/api/v2/collector',
qs.stringify(PX2data),
{
headers: PX2headers,
}
).catch((e) => console.log(e)); // This is optional (use try/catch if you still want)
// set variables
alreadyFetched = true;
cachedData = data;
return data;
}
And you can still use your existing code as normal but this time it will not fetch the data everytime if it was already fetched before.
let testing = async () => {
var a = await sendPx2();
console.log(a)
}
testing();
Upvotes: 1
Reputation: 196
You can store the data on a file
var fs = require("fs");
const util = require('util');
const readFile = util.promisify(fs.readFile);
const expiry = 10*60*1000 // 10 minutes
function cachedFunction(fn){
return async (...params) => {
let path = `${fn.name}:${params.join(":")}.json`
if (fs.existsSync(path)) {
let rawdata = await readFile(path, 'utf-8');
let response = JSON.parse(rawdata.toString());
console.log(response)
if(response.created_at + expiry > Date.now()){
console.log("getting from cache")
return rawdata
}
}
const data = await fn(...params)
if(data && typeof data === 'object'){
const stringifiedData = JSON.stringify({...data,created_at: Date.now()})
fs.writeFileSync(path, stringifiedData);
}
return data
}
}
async function hello(){
return {a:1,b:2}
}
async function test() {
console.log(await cachedFunction(hello)("x"))
}
test()
Upvotes: 0
Reputation: 56
You can store the data inside a JSON file... Using the writeFile function in Node JS :)
fs = require('fs');
fs.writeFile('helloworld.json', px2resp, function (err) {
if (err) return console.log(err);
console.log('Data Written');
});
Then read it from the file to use in the Functions.
fs = require('fs')
fs.readFile('helloworld.json', 'utf8', function (err,data) {
if (err) {
return console.log(err);
}
console.log(data);
});
Make sure to add utf-8
, so it will not return Buffer Data.
Upvotes: 0