Implementing retry logic in node-fetch api call - node.js

I hope you will forgive the beginners question, I'm trying to implement a simple retry policy for an api call using node-fetch
This is being added to an existing repo using TypeScript so I'm using this also, hence the data definitions.
async checkStatus(custId: string, expectedStatus: string) {
const response = await fetch(
`${'env.API_URL'}/api/customer/applications/${custId}`,
{
method: 'GET',
headers: headers,
},
)
expect(response.status, "Response status should be 200").to.be.equal(200)
const resp = await response.json()
expect(resp.status).to.contain(expectedStatus)
return resp.status;
}
I am calling it like so
await this.checkApplicationStatus(custId, 'NEW')
await this.checkApplicationStatus(custId, 'EXISTING')//and so forth
Is there a neat way of retrying based on an unexpected expectedStatus ?
Again, I appreciate there may be many examples out there but as a beginner, I am struggling to see a good/best-practice approach so looking for someone to provide an example. I don't need to use Chai assertions, this was just my first attempt.
TIA

you can check a library that I've published #teneff/with-retry
to use it you'll have to define error classes like these:
class UnexpectedStatus extends Error {
constructor(readonly status: number) {
super("Unexpected status returned from API");
}
}
class ResourceNotFound extends Error {
constructor() {
super("Resource not found in API");
}
}
and throw respectively depending on the status code:
export const getCustomerApplications = async ( custId, headers ) => {
const result = await fetch(`https://example.com/api/customer/applications/${custId}`, {
method: "GET",
headers,
});
if (result.status === 404) {
throw new ResourceNotFound();
} else if (result.status > 200) {
throw new UnexpectedStatus(result.status);
}
return result;
};
and then just use the HOF from the library to wrap your function, with options (how many retries should be attempted and for which errors should it be retrying)
const retryWhenReourceNotFoundOrUnexpectedStatus = withRetry({
errors: [UnexpectedStatus, ResourceNotFound],
maxCalls: 3,
});
const getCustomerApplicationsWithRetry =
retryWhenReourceNotFoundOrUnexpectedStatus(getCustomerApplications);
const result = await getCustomerApplicationsWithRetry(1234, {
Authorization: "Bearer mockToken",
});
Check this working setup

Related

Sample Apollo Client code to test APQ (Automated Persistent Queries)

I was trying to test APQ with a server written in haskell. The following is the sample Apollo client code, I wrote to test it:
const { createPersistedQueryLink } = require("apollo-link-persisted-queries")
const { createHttpLink } = require("apollo-link-http")
const { InMemoryCache } = require("apollo-cache-inmemory")
const { ApolloClient } = require("apollo-client")
const { gql } = require('apollo-server');
const { ApolloLink } = require("apollo-link")
const fetch = require("node-fetch")
const link = ApolloLink.from([
createPersistedQueryLink(),
createHttpLink({
uri: "http://localhost:8080/v1/graphql",
fetch: fetch,
headers: {
"admin-secret":"password"
}
})
]);
const client = new ApolloClient({
cache: new InMemoryCache(),
link: link
})
async function main() {
const response = await client
.query({
query: gql`
query {
child {
name
}
}`
})
console.log(response.data)
}
main().catch(err => console.log("Err:", err))
But whenever I run this file, I get the following error:
graphQLErrors: [
{
extensions: [Object],
message: "the key 'query' was not present"
}
],
When I check the Request body sent in POST Body, I get the following thing:
{"operationName":null,"variables":{},"extensions":{"persistedQuery":{"version":1,"sha256Hash":"0832c514aef4b1a6d84702e8b2fab452cbb0af61f0a1c4a4c30405e671d40527"}}}
It tells that the query is not sent in the Post Body. Which might be the reason I'm getting the above error.
Hence, I am confused at this point :see_no_evil:
I read through a tons of blogs, but It's not clear as to what HTTP method is used when { useGETForHashedQueries: true } option is not given. From my experiment above, it looks as if - POST method is used.
But if POST method is used, why isn't the query sent in the POST body.
BUT
When I use the { useGETForHashedQueries: true } option, it works correctly. What might I be doing wrong here?
It would be really great, if someone would clear this out for me.

Got TS 2739 error while returning value from promise. Type 'Promise<any>' is missing the following properties from type

Currently I'm writing code for request login to server and receive it's session data and send to global context.
Basic principle is 1)Request and get Promise 2)Validate fetch result itself and response status. 3)Provide value to external component. And I'm working on 1) and 2).
But I got an error about data typing Type 'Promise<any>' is missing the following properties from type 'SessionInfo': userEmail, userName, sessionToken, duets(2739) at code that returns result data to external components. Despite of strict data typing(Maybe I think), I'm not sure why linter says Promise not Promise>. I think TS fails to assert it's type.
When I run very similar code with Javascript(without typing), it works in past. I'm not sure why this happens and I don't know what's wrong. Can you check my code?
Codes are below, there's 4 files -- interface definition file related to User, interface definition for handling response json, Actual request fetch, Response validation and evaluation.
When I checked linting at return res.data at actionHandler.ts, linter succeed to predict it's type. res.data is ResponseSet<SessionInfo>.data?: userTypes.SessionInfo as linter said.
In userTypes.ts
export interface SessionInfo {
userEmail: string,
userName: string,
sessionToken: string,
due: number,
}
In commonTypes.ts
export interface ResponseSet<T> { // Response wrapper when it returns with code 200
statusCode: ResponseStatusCode, // ResponseStatusCode is custom typed status code not for request it self.
data?: T,
description?: string,
};
In userReq.ts
const login = async (email: string, password: string): Promise<commonTypes.ResponseSet<userTypes.SessionInfo>> => {
try {
const request: Request = new Request(
composeUri(`user/login`, { email, password }),
{
method: 'GET',
headers: { 'Content-type': 'application/json' },
mode: 'cors',
}
);
const response: Response = await fetch(request);
if (response.status != 200) throw response.status;
return await response.json();
} catch {
return {
statusCode: 1,
};
}
}
In actionHandler.ts
export const doLogin = (email: string, password: string): userTypes.SessionInfo => {
const result: userTypes.SessionInfo = userReq.login(email, password)
.then(res => {
if (res.statusCode != 0) throw new Error(res.description || 'UnknownError');
return res.data;
})
.catch(err => {
return null;
});
return result;
}
Where I got an error is const result:.... I got Type 'Promise<any>' is missing the following properties from type 'SessionInfo': userEmail, userName, sessionToken, due ts(2739). I'm not sure why it is recognized as 'Promise` despite of strict type definition of my code.
the issue is that result isn't SessionInfo. It is a Promise of it.
const result: Promisse<userTypes.SessionInfo | null>;
doLogin is async due to used promise, you should follow async await inside and it can't return userTypes.SessionInfo, result will be a promise.
export const doLogin = async (email: string, password: string): Promise<userTypes.SessionInfo | null> => {
try {
const result: commonTypes.ResponseSet<userTypes.SessionInfo> = await userReq.login(email, password);
if (res.statusCode != 0) throw new Error(res.description || 'UnknownError');
} catch (e) {
return null;
}
return res.data;
}
// somewhere in the code (async env)
await doLogin(email, password);

Mock multiple api call inside one function using Moxios

I am writing a test case for my service class. I want to mock multiple calls inside one function as I am making two API calls from one function. I tried following but it is not working
it('should get store info', async done => {
const store: any = DealersAPIFixture.generateStoreInfo();
moxios.wait(() => {
const request = moxios.requests.mostRecent();
request.respondWith({
status: 200,
response: store
});
const nextRequest = moxios.requests.at(1);
nextRequest.respondWith({
status: 200,
response: DealersAPIFixture.generateLocation()
});
});
const params = {
dealerId: store.dealerId,
storeId: store.storeId,
uid: 'h0pw1p20'
};
return DealerServices.retrieveStoreInfo(params).then((data: IStore) => {
const expectedOutput = DealersFixture.generateStoreInfo(data);
expect(data).toMatchObject(expectedOutput);
});
});
const nextRequest is always undefined
it throw error TypeError: Cannot read property 'respondWith' of undefined
here is my service class
static async retrieveStoreInfo(
queryParam: IStoreQueryString
): Promise<IStore> {
const res = await request(getDealerStoreParams(queryParam));
try {
const locationResponse = await graphQlRequest({
query: locationQuery,
variables: { storeId: res.data.storeId }
});
res.data['inventoryLocationCode'] =
locationResponse.data?.location?.inventoryLocationCode;
} catch (e) {
res.data['inventoryLocationCode'] = 'N/A';
}
return res.data;
}
Late for the party, but I had to resolve this same problem just today.
My (not ideal) solution is to use moxios.stubRequest for each request except for the last one. This solution is based on the fact that moxios.stubRequest pushes requests to moxios.requests, so, you'll be able to analyze all requests after responding to the last call.
The code will look something like this (considering you have 3 requests to do):
moxios.stubRequest("get-dealer-store-params", {
status: 200,
response: {
name: "Audi",
location: "Berlin",
}
});
moxios.stubRequest("graph-ql-request", {
status: 204,
});
moxios.wait(() => {
const lastRequest = moxios.requests.mostRecent();
lastRequest.respondWith({
status: 200,
response: {
isEverythingWentFine: true,
},
});
// Here you can analyze any request you want
// Assert getDealerStoreParams's request
const dealerStoreParamsRequest = moxios.requests.first();
expect(dealerStoreParamsRequest.config.headers.Accept).toBe("application/x-www-form-urlencoded");
// Assert graphQlRequest
const graphQlRequest = moxios.requests.get("POST", "graph-ql-request");
...
// Assert last request
expect(lastRequest.config.url).toBe("status");
});

Unit Testing NodeJs Controller with Axios

I have a controller and a request file that look like this, making the requests with axios(to an external API), and sending the controller response to somewhere else, my question is, how to apply Unit Testing to my controller function (getInfoById), how do I mock the axiosRequest since it's inside the controller?. I am using Jest and only Jest for testing(might need something else, but I'm not changing)
file: axiosFile.js
import axios from "axios"
export const axiosRequest = async (name) => {
const { data } = await axios.get("url")
return data
}
file: controllerFile.js
import { axiosRequest } from "./axiosFile"
export const getInfoById = async (name) => {
try {
const response = await axiosRequest(name)
return { status: 200, ...response }
} catch {
return { status: 500, { err: "Internal ServerError" } }
}
}
Thanks in advance.
PS: It's a Backend in NodeJs
You can mock the http calls using nock
This way you will be directly able to test your method by mocking the underlying http call. So in your case something like
const nock = require('nock')
const scope = nock(url)
.get('/somepath')
.reply(200, {
data: {
key: 'value'
},
})

Extensions not returned in GraphQL query results

I'm creating an Apollo Client like this:
var { ApolloClient } = require("apollo-boost");
var { InMemoryCache } = require('apollo-cache-inmemory');
var { createHttpLink } = require('apollo-link-http');
var { setContext } = require('apollo-link-context');
exports.createClient = (shop, accessToken) => {
const httpLink = createHttpLink({
uri: `https://${shop}/admin/api/2019-07/graphql.json`,
});
const authLink = setContext((_, { headers }) => {
return {
headers: {
"X-Shopify-Access-Token": accessToken,
"User-Agent": `shopify-app-node 1.0.0 | Shopify App CLI`,
}
}
});
return new ApolloClient({
cache: new InMemoryCache(),
link: authLink.concat(httpLink),
});
};
to hit the Shopify GraphQL API and then running a query like that:
return client.query({
query: gql` {
productVariants(first: 250) {
edges {
node {
price
product {
id
}
}
cursor
}
pageInfo {
hasNextPage
}
}
}
`})
but the returned object only contain data and no extensions which is a problem to figure out the real cost of the query.
Any idea why?
Many thanks for your help
There's a bit of a hacky way to do it that we wrote up before:
You'll need to create a custom apollo link (Apollo’s equivalent of middleware) to intercept the response data as it’s returned from the server, but before it’s inserted into the cache and the components re-rendered.
Here's an example were we pull metrics data from the extensions in our API:
import { ApolloClient, InMemoryCache, HttpLink, ApolloLink } from 'apollo-boost'
const link = new HttpLink({
uri: 'https://serve.onegraph.com/dynamic?show_metrics=true&app_id=<app_id>',
})
const metricsWatchers = {}
let id = 0
export function addMetricsWatcher(f) {
const watcherId = (id++).toString(36)
metricsWatchers[watcherId] = f
return () => {
delete metricsWatchers[watcherId]
}
}
function runWatchers(requestMetrics) {
for (const watcherId of Object.keys(metricsWatchers)) {
try {
metricsWatchers[watcherId](requestMetrics)
} catch (e) {
console.error('error running metrics watcher', e)
}
}
}
// We intercept the response, extract our extensions, mutatively store them,
// then forward the response to the next link
const trackMetrics = new ApolloLink((operation, forward) => {
return forward(operation).map(response => {
runWatchers(
response
? response.extensions
? response.extensions.metrics
: null
: null
)
return response
})
})
function create(initialState) {
return new ApolloClient({
link: trackMetrics.concat(link),
cache: new InMemoryCache().restore(initialState || {}),
})
}
const apolloClient = create(initialState);
Then to use the result in our React components:
import { addMetricsWatcher } from '../integration/apolloClient'
const Page = () => {
const [requestMetrics, updateRequestMetrics] = useState(null)
useEffect(() => {
return addMetricsWatcher(requestMetrics =>
updateRequestMetrics(requestMetrics)
)
})
// Metrics from extensions are available now
return null;
}
Then use a bit of mutable state to track each request and its result, and the use that state to render the metrics inside the app.
Depending on how you're looking to use the extensions data, this may or may not work for you. The implementation is non-deterministic, and can have some slight race conditions between the data that’s rendered and the data that you've extracted from the extensions.
In our case, we store performance metrics data in the extensions - very useful, but ancillary - so we felt the tradeoff was acceptable.
There's also an open issue on the Apollo client repo tracking this feature request
I dont have any idea of ApolloClient but i tried to run your query in shopify graphql app. It return results with extensions. Please find screenshot below. Also You can put questions in ApolloClient github.

Resources