use [err, res] pattern for server axios

This commit is contained in:
ntr committed 2023-02-08 22:51:09 +11:00
1 parent 306dc30499
commit 2ffb5f9bc3
2 files changed
+41 -20

No files matched your search

+3
View File
@@ -8,6 +8,9 @@ discord bot
email ppl who signed up email ppl who signed up
say we have updates say we have updates
order by dropdown for main list
sample offer with tooltips
go over and reorganise event logic go over and reorganise event logic
should be connection.service ? should be connection.service ?
+38 -20
View File
@@ -10,9 +10,19 @@ import type { PrismaClient, Want, User, Listing } from '@prisma/client';
import { logAxiosError, wantDetails } from './utils'; import { logAxiosError, wantDetails } from './utils';
import { Pg } from './pg'; import { Pg } from './pg';
// margh type ApiResponse = [string | null, any | null];
// vanderbabe
// jmcdermid1 declare module 'axios' {
export interface AxiosInstance {
request(config: AxiosRequestConfig): Promise<ApiResponse>;
get(url: string, config?: AxiosRequestConfig): Promise<ApiResponse>;
delete(url: string, config?: AxiosRequestConfig): Promise<ApiResponse>;
head(url: string, config?: AxiosRequestConfig): Promise<ApiResponse>;
post(url: string, data?: any, config?: AxiosRequestConfig): Promise<ApiResponse>;
put(url: string, data?: any, config?: AxiosRequestConfig): Promise<ApiResponse>;
patch(url: string, data?: any, config?: AxiosRequestConfig): Promise<ApiResponse>;
}
}
export default function createDiscogs(log: Log, pg: Pg) { export default function createDiscogs(log: Log, pg: Pg) {
const TOKEN = 'Discogs token=wRTXuYZGOPsIQgKRGKCAkUkidGtvpSfQgPWkYIpD'; const TOKEN = 'Discogs token=wRTXuYZGOPsIQgKRGKCAkUkidGtvpSfQgPWkYIpD';
@@ -28,24 +38,27 @@ export default function createDiscogs(log: Log, pg: Pg) {
}); });
function onSuccess(response) { function onSuccess(response) {
return response; return [null, response.data];
} }
function onError(error) { function onError(error) {
// if (error.response) return [error.response.data.error, null]; console.error(error);
// if (error.request) return ['Network Error', null];
// return ['Unknown Error', null];
if (error.response.status === 429) { if (error.response.status === 429) {
throw new Error('rate limited, try again in 1 minute'); return [new Error('rate limited, try again in 1 minute'), null];
} }
if (error.response) return [error.response.data, null];
if (error.request) return ['Network Error', null];
return ['Unknown Error', null];
} }
api.interceptors.response.use(onSuccess, onError); api.interceptors.response.use(onSuccess, onError);
async function wantListSync(username: string, user: User): Promise<Want[]> { async function wantListSync(username: string, user: User): Promise<Want[]> {
const { data: { wants, pagination }} = await api.get(`${apiBase}/users/${username}/wants`); const [err, res] = await api.get(`${apiBase}/users/${username}/wants`);
const releases = await Promise.all(wants.map(want => release(want.id))); log.warn(err, res);
if (err) throw err;
const { wants, pagination } = res;
const releases = await Promise.all(wants.map(want => release(want.id)));
log.info({ wants: wants.length, user: username, userId: user.id }, 'fetched discogs wantlist'); log.info({ wants: wants.length, user: username, userId: user.id }, 'fetched discogs wantlist');
// TODO filter releases to be vinyl format only // TODO filter releases to be vinyl format only
@@ -62,7 +75,7 @@ export default function createDiscogs(log: Log, pg: Pg) {
} }
async function release(id: DiscogsRelease): Promise<any> { async function release(id: DiscogsRelease): Promise<any> {
const { data } = await api.get(`${apiBase}/releases/${id}`); const [error, data] = await api.get(`${apiBase}/releases/${id}`);
return data; return data;
} }
@@ -71,18 +84,23 @@ export default function createDiscogs(log: Log, pg: Pg) {
url.searchParams.append('query', query); url.searchParams.append('query', query);
url.searchParams.append('type', 'release'); url.searchParams.append('type', 'release');
url.searchParams.append('format', 'vinyl'); url.searchParams.append('format', 'vinyl');
const { data: { results } } = await api.get(url.href); const [err, res] = await api.get(url.href);
if (err) throw err;
const { results } = res;
return results; return results;
} }
async function inventory(user: string) { async function inventory(user: string) {
const res = await api.get(`${apiBase}/users/${user}/inventory`); const [err, res] = await api.get(`${apiBase}/users/${user}/inventory`);
return res.data.listings; if (err) throw err;
return res.listings;
} }
async function listings(want: Want) { async function listings(want: Want) {
const res = await api.get(`https://www.discogs.com/sell/release/${want.release}?limit=250`); const [err, res] = await api.get(`https://www.discogs.com/sell/release/${want.release}?limit=250`);
const $ = cheerio.load(res.data); if (err) throw err;
const $ = cheerio.load(res);
const ids = $('.item_description_title[href]') const ids = $('.item_description_title[href]')
.map(function getListingId() { .map(function getListingId() {
const id = Number.parseInt(this.attribs.href.replace('/sell/item/', ''), 10); const id = Number.parseInt(this.attribs.href.replace('/sell/item/', ''), 10);
@@ -102,9 +120,9 @@ export default function createDiscogs(log: Log, pg: Pg) {
if (listing) return listing; if (listing) return listing;
log.debug('fetching listing', id); log.debug('fetching listing', id);
const res = await api.get(`${apiBase}/marketplace/listings/${id}`); const [err, discogsListing] = await api.get(`${apiBase}/marketplace/listings/${id}`);
log.debug(res.data); log.debug(discogsListing);
return pg.listingUpsert(res.data, want); return pg.listingUpsert(discogsListing, want);
} }
return { return {