I have this piece of code that I would like to refactor:
import handler from "./libs/handler.js";
import fetch from "node-fetch";
async function checkResponseStatus(res) {
if(res.status >= 400) {
throw new Error(await res.text());
} else {
return res;
}
}
export const lambda = handler(async (event, context) => {
const api = process.env.IEXSandbox ? "sandbox" : "cloud";
const ticker = event.ticker.toLowerCase();
const token = process.env.IEXPublishableToken;
const version = process.env.IEXVersion;
const req = `https://${api}.iexapis/${version}/stock/${ticker}/quote?token=${token}`;
const res = await fetch(req).then(checkResponseStatus);
return await res.json();
});
It's essentially a fetch
into a 3rd party API, namely IEXCloud, it works fine and does its job. However, I would like to do some work on the response before returning it, so I can simply do this instead:
const res = await fetch(req).then(checkResponseStatus);
const x = await res.json();
return xpanyName;
However, I feel like this is pretty clunky. I would like to know if I can only define a single object instead of having both res
and x
. This can be done my way, but I want to know for learning purposes. Thank you for reading!
I have this piece of code that I would like to refactor:
import handler from "./libs/handler.js";
import fetch from "node-fetch";
async function checkResponseStatus(res) {
if(res.status >= 400) {
throw new Error(await res.text());
} else {
return res;
}
}
export const lambda = handler(async (event, context) => {
const api = process.env.IEXSandbox ? "sandbox" : "cloud";
const ticker = event.ticker.toLowerCase();
const token = process.env.IEXPublishableToken;
const version = process.env.IEXVersion;
const req = `https://${api}.iexapis./${version}/stock/${ticker}/quote?token=${token}`;
const res = await fetch(req).then(checkResponseStatus);
return await res.json();
});
It's essentially a fetch
into a 3rd party API, namely IEXCloud, it works fine and does its job. However, I would like to do some work on the response before returning it, so I can simply do this instead:
const res = await fetch(req).then(checkResponseStatus);
const x = await res.json();
return x.panyName;
However, I feel like this is pretty clunky. I would like to know if I can only define a single object instead of having both res
and x
. This can be done my way, but I want to know for learning purposes. Thank you for reading!
- This is not a good question for SO. Had it had more meat on it, it could perhaps be a question for codereview – mplungjan Commented May 15, 2020 at 7:39
2 Answers
Reset to default 11You can also nested async await syntax on ECMAScript 2017 like this:
const data = await (await fetch('api/route')).json();
You can try instead of a new variable called x to catch in a then()
like this:
const res = await fetch(req)
.then(checkResponseStatus)
.then(res => res.json());