Catch Google Cloud function errors in POST - javascript

I have this cloud function that append a line to a Google Spreadsheet:
function addLine(req, res) {
res.set("Access-Control-Allow-Origin", "*");
if (req.method === "OPTIONS") {
res.set("Access-Control-Allow-Methods", "POST");
res.set("Access-Control-Allow-Headers", "Content-Type");
res.set("Access-Control-Max-Age", "3600");
return res.status(204).send("");
}
const isReqValid = validateReq(req);
if (!isReqValid) return res.send("Not valid request!"); // <--
const { body } = req;
const isBodyValid = validateData(body);
if (!isBodyValid) return res.send("Not valid payload!"); // <--
return appendData(body)
.then(() => res.send("Added line"))
.catch((err) => {
res.send("Generic error!");
});
}
function validateReq(req) {
if (req.method !== "POST") return false;
return true;
}
function validateData(data) {
// do something and return true or false
}
async function appendData(data) {
const client = await auth.getClient();
return sheets.spreadsheets.values.append(
{
spreadsheetId: ...,
auth: client,
range: "A1:B",
valueInputOption: "RAW",
resource: { values: [data] },
},
);
}
I use it in this way:
async collaborate(data: CollaborateDatum) {
await post('...cloudfunctions.net/addLine', data)
}
async function post(url, data) {
return fetch(url, {
method: 'POST',
headers: {
Accept: 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify(data),
})
}
How can I "read" the errors Not valid request! and Not valid payload!? Because if I tried to append a line with not valid data, I get status code 200 but in Chrome Dev Tools -> Network -> Response, the response is Not valid payload! but I don't know how to catch this error.
Thanks a lot!

You should be able to get any response text that's passed back like this:
let responseText = await (await post('...cloudfunctions.net/addLine', data)).text();

Related

How to wait until request.get finish then conduct the next block in node.js

I am new to NodeJS and I am working on a request.get problem. My goal is simply have a function that request the web, and when request finished, the function returns the result, otherwise it returns an error message.
Here's the function that I used for request:
var artistNameIdMap = {};
var getPopularArtists = async () => {
//https://nodejs.org/api/http.html#http_http_request_options_callback
var options = {
url: CONSTANTS.API_ENDPOINTS.playlist_endpoint + subpath,
headers: { 'Authorization': 'Bearer ' + access_token,
'Accept': 'application/json',
'Content-Type': 'application/json'},
json: true
}
request.get(options, function(error, response, body) {
if (response.statusCode === 200){
console.log("inside");
artistNameIdMap = getArtistNameIdMap(body, artistNameIdMap);
} else {
res.send("get popular error");
return {};
}
})
console.log("outside");
return artistNameIdMap;
module.exports = {
GetPopularArtists: getPopularArtists
}
And this function is included in a getPopular.js file. I would like to call the function in another file playlist.js.
In playlist.js, I wrote
const getPopular = require('./controllers/getPopular');
router.get("/BPM/:BPM", (req, res) =>{
const artistNameIdMap = getPopular.GetPopularArtists();
console.log(artistNameIdMap);
let BPM = req.params.BPM;
res.send(BPM);
})
However the result I got is
outside
Promise { {} }
inside
It seems like the return was before the request gives back the information. I wonder what should I write to make sure that I can obtain the correct artistNameIdMap at playlist.js.
Though you've already accepted an answer, there are a couple of additional things I can add. First, the request() library has been deprecated and it is not recommended for new code. Second, there is a list of recommended alternatives here. Third, all these alternatives support promises natively as that is the preferred way to program asynchronous code in modern nodejs programming.
My favorite alternative is got() because I find it's interface simple and clean to use and it has the features I need. Here's how much simpler your code would be using got():
const got = require('got');
let artistNameIdMap = {};
async function getPopularArtists() {
const options = {
headers: { 'Authorization': 'Bearer ' + access_token,
'Accept': 'application/json',
'Content-Type': 'application/json'},
};
const url = CONSTANTS.API_ENDPOINTS.playlist_endpoint + subpath;
let results = await got(url, options).json();
// update local cache object
artistNameIdMap = getArtistNameIdMap(results, artistNameIdMap);
return artistNameIdMap;
}
module.exports = {
GetPopularArtists: getPopularArtists
}
Note: The caller should supply error handling based on the returned promise.
GetPopularArtists().then(results => {
console.log(results);
}).catch(err => {
console.log(err);
});
Since you want to use Promises, use it like this
const getPopularArtists = () => new Promise((resolve, reject) {
const options = {
url: CONSTANTS.API_ENDPOINTS.playlist_endpoint + subpath,
headers: {
'Authorization': 'Bearer ' + access_token,
'Accept': 'application/json',
'Content-Type': 'application/json'
},
json: true
}
request.get(options, (error, response, body) => {
if (error) {
reject(error);
} else if (response.statusCode === 200) {
console.log("inside");
resolve(getArtistNameIdMap(body, artistNameIdMap));
} else {
reject("get popular error");
}
});
});
module.exports = {
GetPopularArtists: getPopularArtists
}
And use it like
const getPopular = require('./controllers/getPopular');
router.get("/BPM/:BPM", async (req, res) =>{
try {
const artistNameIdMap = await getPopular.GetPopularArtists();
console.log(artistNameIdMap);
let BPM = req.params.BPM;
res.send(BPM);
} catch(err) {
res.send(err);
}
})
Alternatively, without promises, you'll need to use a callback
Using callbacks:
const getPopularArtists = (callback) => {
const options = {
url: CONSTANTS.API_ENDPOINTS.playlist_endpoint + subpath,
headers: { 'Authorization': 'Bearer ' + access_token,
'Accept': 'application/json',
'Content-Type': 'application/json'},
json: true
}
request.get(options, function(error, response, body) {
if (error) {
callback(error);
} else if (response.statusCode === 200){
console.log("inside");
callback(null, getArtistNameIdMap(body, artistNameIdMap));
} else {
callback("get popular error");
}
})
};
module.exports = {
GetPopularArtists: getPopularArtists
}
And use it like:
const getPopular = require('./controllers/getPopular');
router.get("/BPM/:BPM", (req, res) =>{
getPopular.GetPopularArtists((err, artistNameIdMap) => {
if (err) {
// handle error here
} else {
console.log(artistNameIdMap);
let BPM = req.params.BPM;
res.send(BPM);
}
});
});

Callback function with request method to third party API is not working

I am a beginner to callback concept and looking for a solution to my problem.
I calling third party API using request package in node.js here is the code:
In reusable library file: auth.js
let getAuthToken = () => {
let authToken;
var options = {
'method': 'GET',
'url': 'https://<apiURL>/V1/auth_token',
'headers': {
'Authorization': 'Basic <token>'
}
};
request(options, (error, response) => {
if (error) {
throw new Error(error);
} else {
authToken = JSON.parse(response.body);
}
});
return authToken;
}
on my route: http://127.0.0.1:3000/api/v1/musics/authorize-account, I am calling my controller function named "getAuthorizationToken()"
controllerfile: music.controller.js
const auth = require('../middleware/auth');
let getAuthorizationToken = async (req, res, next) => {
let token = await auth.getAuthToken();
console.log(auth.getAuthToken());
res.send(token);
}
Problem is the controller function is getting executed completely and then the third party API is being called event I have added await to the function.
Do explain to me the problem I am facing and any workaround solution will be heartily helpful.
You have to return a promise to be able to await something and have it work as expected:
let getAuthToken = () => {
let authToken;
var options = {
'method': 'GET',
'url': 'https://<apiURL>/V1/auth_token',
'headers': {
'Authorization': 'Basic <token>'
}
};
return new Promise((resolve, reject) => {
request(options, (error, response) => {
if (error) {
reject(error);
} else {
authToken = JSON.parse(response.body);
resolve(authToken);
}
});
})
}
await is only useful on promises. In your case your getAuthToken does not return an promise. But you can change it.
let getAuthToken = () => {
return new Promise((res, rej) => {
let authToken;
var options = {
method: "GET",
url: "https://<apiURL>/V1/auth_token",
headers: {
Authorization: "Basic <token>"
}
};
request(options, (error, response) => {
if (error) {
rej(error);
} else {
authToken = JSON.parse(response.body);
res(authToken);
}
});
});
};
In addition you should also wrap your await in a try / catch
let getAuthorizationToken = async (req, res, next) => {
try {
let token = await auth.getAuthToken();
console.log(token);
return res.send(token);
} catch(err) {
console.log(err);
return res.status(500).send(err);
}
}
Instead of an 500 error you should send an different error code like:
400 Bad request: If there are some missing credentials like the token is missing
401 Unauthorized: If the token is wrong

Using Fetch API, how do I access JSON data when handling errors

Our API server returns JSON data with error responses. I could not find a standard way of handling JSON data on error handling methods. my current solution is this. It is working, but I want to handle errors in catch() method not in then();
let url = 'http://localhost:8080';
let data = {'field': 'value'};
fetch(url, {
method: 'PUT',
body: JSON.stringify(data),
credentials: 'same-origin',
mode: 'cors',
headers: {
'content-type': 'application/json',
'accept': 'application/json'
}
})
.then(res => {
if (res.status == 400) {
return res.json();
} else if (!res.ok) {
throw (res);
} else {
return res.json();
}
}).then(data => {
if (data.status == 400) {
throw (data);
}
return (data);
}).catch(err => {
if (err.status == 400) {
throw this.handleError(err);
} else {
throw new Error(`HTTP Error ${err.status}`);
}
});
this is an example of JSON response from server.
{
"parameters": {
"type": {
"isEmpty": "Field is required and cannot be empty"
},
"from": {
"isEmpty": "Field is required and cannot be empty"
},
"to": {
"isEmpty": "Field is required and cannot be empty"
}
},
"title": "Invalid parameter",
"type": "/api/doc/invalid-parameter",
"status": 400,
"detail": "Invalid parameter"
}
I would make a thin wrapper around fetch which throws on >= 400 responses with parsed body else parses successful responses.
function parse(res) {
const contentType = res.headers.get('Content-Type') || '';
const isJson = contentType.includes('application/json');
return isJson ? res.json() : res;
}
async function throwOnError(res) {
if (res.status >= 400) {
const err = new Error(res.statusText || 'Internal Server Error');
err.status = res.status;
const parsedRes = await parse(res);
err.body = parsedRes;
throw err;
}
return res;
}
async function fetchWrapper({ method, url, data, headers }) {
const combinedHeaders = {
'Content-Type': 'application/json',
'Accept': 'application/json',
};
if (headers) {
Object.assign(combinedHeaders, headers);
}
const options = {
credentials: 'same-origin',
mode: 'cors',
method,
headers: combinedHeaders,
};
if (data) {
options.body = JSON.stringify(data);
}
return fetch(url, options)
.then(throwOnError)
.then(parse);
}
const queryParams = (params) =>
Object.keys(params)
.filter(k => params[k] !== null && typeof params[k] !== 'undefined')
.map(k => `${encodeURIComponent(k)}=${encodeURIComponent(params[k])}`)
.join('&');
export const appendUrlParams = (url, params) => (params ? `${url}?${queryParams(params)}` : url);
export const $get = (url, params, { ...options }) =>
fetchWrapper({ method: 'GET', url: appendUrlParams(url, params), ...options });
export const $del = (url, params, { ...options }) =>
fetchWrapper({ method: 'DELETE', url: appendUrlParams(url, params), ...options });
export const $post = (url, data, { ...options }) =>
fetchWrapper({ method: 'POST', url, data, ...options });
export const $put = (url, data, { ...options }) =>
fetchWrapper({ method: 'PUT', url, data, ...options });
e.g.
async function fetchSomething() {
try {
const res = await $get('someurl');
// Do something with successful `res`.
} catch (err) {
console.error(err);
// err.status -> the status of the response
// err.body -> the body of the response
}
}
Or use then/catch if that's your preference.

Axios multiple request on interceptor

I'm using the library axios in my react app.
I'm having a problem with the interceptor.
My question is let say I have three requests happening concurrently and I don't have the token, the interceptor calling the getUserRandomToken three time, I want the interceptor will wait until I'm getting the token from the first request and then continue to the others.
P.S. the token he is with an expiration date so I also checking for it and if the expiration date is not valid I need to create a new token.
This is the interceptor:
axios.interceptors.request.use(
config => {
/*I'm getting the token from the local storage
If there is any add it to the header for each request*/
if (tokenExist()) {
config.headers.common["token"] = "...";
return config;
}
/*If there is no token i need to generate it
every time create a random token, this is a axios get request*/
getUserRandomToken()
.then(res => {
/*add the token to the header*/
config.headers.common["token"] = res;
return config;
})
.catch(err => {
console.log(err);
});
},
function(error) {
// Do something with request error
return Promise.reject(error);
}
);
How about singleton object that will handle the token generations? something similar to this:
const tokenGenerator ={
getTokenPromise: null,
token: null,
getToken(){
if (!this.getTokenPromise){
this.getTokenPromise = new Promise(resolve=>{
/*supposed to be a http request*/
if (!this.token){
setTimeout(()=>{
this.token = 'generated';
resolve(this.token);
},0)
}else{
resolve(this.token);
}
})
}
return this.getTokenPromise;
}
you can reference this same object from the interceptors.
see example: JS FIddle
reference: reference
You can return a Promise from interceptor callback to "wait" until promise fullfiles (this will fit your case). Check out this example:
function axiosCall () {
return new Promise((resolve, reject) => {
Axios.post(URL, {apiKey}).then((response) => {
resolve(response.data.message);
}).catch((error) => {
reject(error);
});
});
}
instance.interceptors.request.use((config) => {
return axiosCall().then((tokenResponse) => {
setWebCreds(tokenResponse);
config.headers.Authorization = `Bearer ${tokenResponse}`;
return Promise.resolve(config)
}).catch(error => {
// decide what to do if you can't get your token
})
}, (error) => {
return Promise.reject(error);
});
More details here: https://github.com/axios/axios/issues/754
Following code doing certain tasks:
Update Token on 401
Make a queue of failed requests while the token is refreshing.
Restore the original request after token refreshing.
Once the peculiar request is given 200, remove it from the queue.
Config.js
import axios from 'axios';
import { AsyncStorage } from 'react-native';
import { stateFunctions } from '../../src/sharedcomponent/static';
const APIKit = axios.create({
baseURL: '',
timeout: 10000,
withCredentials: true,
});
const requestArray = [];
// Interceptor for Request
export const setClientToken = token => {
APIKit.interceptors.request.use(
async config => {
console.log('Interceptor calling');
let userToken = await AsyncStorage.getItem('userToken');
userToken = JSON.parse(userToken);
config.headers = {
'Authorization': `Bearer ${userToken}`,
'Accept': 'application/json',
"Content-Type": "application/json",
"Cache-Control": "no-cache",
}
// console.log('caling ' , config)
return config;
},
error => {
Promise.reject(error)
});
};
// Interceptor for Response
APIKit.interceptors.response.use(
function (response) {
if (requestArray.length != 0) {
requestArray.forEach(function (x, i) {
if (response.config.url == x.url) {
requestArray.splice(i, 1);
}
});
}
return response;
},
function (error) {
const originalRequest = error.config;
requestArray.push(originalRequest);
let reqData = "username=" + number + "&password=" + pin + "&grant_type=password" + "&AppType=2" + "&FcmToken=null";
// console.log('error ' , error);
if (error.message === "Request failed with status code 401" || error.statuscode === 401) {
if (!originalRequest._retry) {
originalRequest._retry = true;
return axios({
method: 'post',
url: '/api/login',
data: reqData,
headers: {
"Content-Type": "application/x-www-form-urlencoded",
"Cache-Control": "no-cache",
}
})
.then(res => {
let response = res.data;
console.log('successfull Login', response)
if (res.data.StatusCode == 200) {
AsyncStorage.setItem('userToken', JSON.stringify(response.access_token));
stateFunctions.UserId = response.UserId;
stateFunctions.CustomerContactID = response.CustomerContactID;
let obj = {
access_token: response.access_token,
token_type: response.token_type,
expires_in: response.expires_in,
UserId: response.UserId,
CustomerContactID: response.CustomerContactID,
Mobile: response.Mobile,
StatusCode: response.StatusCode
}
AsyncStorage.setItem('logindetail', JSON.stringify(obj));
if (requestArray.length != 0) {
requestArray.forEach(x => {
try {
console.log(x, "request Url");
x.headers.Authorization = `Bearer ${response.access_token}`;
x.headers["Content-Type"] = "application/x-www-form-urlencoded";
APIKit.defaults.headers.common["Authorization"] = `Bearer${response.access_token}`;
APIKit(x)
} catch (e) {
console.log(e)
}
});
}
return APIKit(originalRequest);
}
})
.catch(err => {
console.log(err);
});
}
}
return Promise.reject(error);
}
);
export default APIKit;
Home.js
gettingToken = async () => {
let userToken = await AsyncStorage.getItem('userToken');
userToken = JSON.parse(userToken);
await setClientToken(userToken);
}

How to return the result of an Azure Function

I'm starting with Azure Functions. I have the following code:
module.exports = function (context, req)
{
context.log('JavaScript HTTP trigger function processed a request.');
context.log(context.req.body.videoId)
if (context.req.body.videoId =! null)
{
context.log('inicia a obtener comentarios')
const fetchComments = require('youtube-comments-task')
fetchComments(req.body.videoId)
.fork(e => context.log('ERROR', e), p => {
context.log('comments', p.comments)
})
context.res = { body: fetchComments.comments }
}
else {
context.res = {
status: 400,
body: "Please pass a videoId on the query string or in the request body"
};
}
context.done();
};
How can I return the JSON that fetchComments returns?
Move assigning context.res and call to context.done to promise callback. Set Content-Type to application/json in the headers. Based on your code, something like
if (context.req.body.videoId =! null) {
context.log('inicia a obtener comentarios')
const fetchComments = require('youtube-comments-task')
fetchComments(req.body.videoId)
.fork(e => context.log('ERROR', e), p => {
context.log('comments', p.comments);
context.res = {
headers: { 'Content-Type': 'application/json' },
body: p.comments
};
context.done();
});
}
else {
context.res = {
status: 400,
body: "Please pass a videoId on the query string or in the request body"
};
context.done();
}

Categories

Resources