Skip to content

Instantly share code, notes, and snippets.

@studiocadogan
Created July 23, 2019 16:29
Show Gist options
  • Save studiocadogan/aa7e6513d62cce5f27d255edc58eb763 to your computer and use it in GitHub Desktop.
Save studiocadogan/aa7e6513d62cce5f27d255edc58eb763 to your computer and use it in GitHub Desktop.
import axios from "axios";
import buildUrl from "build-url";
import { setupCache } from "axios-cache-adapter";
import { axiosResponseDataUnpacker } from "axios-data-unpacker";
import getConfig from "next/config";
import _ from "lodash";
import isNode from "detect-node";
import { cacheInstance } from "../cache/redisCache";
const serverCache = cacheInstance;
const env = getConfig?.()?.publicRuntimeConfig?.env;
const manageAPIErrors = (err) => {
console.error(err);
const messageIfExists = err.message || "An Error has occurred";
const transpileError = ({ message, parameters }) => {
if (parameters) {
let newMessage = message;
const keyToIndex = key => (!Number.isNaN(key) ? key + 1 : key);
_.forEach(parameters, (param, key) => {
newMessage = newMessage.replace(`%${keyToIndex(key)}`, param);
});
return newMessage || messageIfExists;
}
return message || messageIfExists;
};
const message = err.response ? transpileError(err.response.data) : messageIfExists;
const statusCode = err.response && err.response.status;
const thrownError = {
message, name: "MagentoApiCallError", statusCode, silent: true,
};
throw thrownError;
};
const { adapter } = setupCache({
maxAge: 10,
exclude: {
query: false,
},
});
const axiosApi = axios.create({
adapter: !isNode && adapter,
});
axiosResponseDataUnpacker(axiosApi);
export const apiRuntime = async ({
url, method = "GET", cacheResponse, ...options
}) => {
if (serverCache && cacheResponse) {
const cacheData = await serverCache.get(url);
if (cacheData) {
return cacheData;
}
}
if (env.NODE_ENV !== "production") {
console.log("Request to: ", url);
}
const data = await axiosApi({
method,
url,
headers: {
...options.headers,
},
...options,
})
.catch(manageAPIErrors);
if (serverCache && cacheResponse) {
serverCache.set(url, data);
}
return data;
};
export const apiPost = async ({
baseUrl = env?.API_URL,
method,
path,
queryParams,
...options
}) => {
const url = buildUrl(baseUrl, {
path,
queryParams,
});
const postData = await apiRuntime({
url,
...options,
method: method || "POST",
});
return postData;
};
export const api = async ({
baseUrl = env?.API_URL,
path,
queryParams,
...options
}) => {
const url = buildUrl(baseUrl, {
path,
queryParams,
});
const data = await apiRuntime({
url,
...options,
});
return data;
};
import redis from "redis";
import { promisify } from "util";
const redisCache = redis.createClient(process.env.REDIS_PORT, process.env.REDIS_HOST);
redisCache
.on("connect", () => console.log("Redis client connected"))
.on("error", err => console.log(`Error ${err}`));
const promisifiedCache = promisify(redisCache.get).bind(redisCache);
export const set = (redisKey, data, ex = "EX", timeout = 300) => redisCache.set(redisKey, JSON.stringify(data), ex, timeout);
export const get = url => promisifiedCache(url).then(res => JSON.parse(res));
export const cacheInstance = {
get,
set,
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment