mkmrare/lib/api.ts

102 lines
2.4 KiB
TypeScript
Raw Normal View History

2019-11-21 12:09:51 +00:00
import { stringify } from "querystring";
2019-11-23 15:20:58 +00:00
import * as request from "request";
2019-11-21 12:09:51 +00:00
2019-11-21 15:56:34 +00:00
import { Article } from "./types";
2019-11-21 12:09:51 +00:00
const URI = "https://api.cardmarket.com/ws/v2.0/output.json";
2019-11-21 16:06:46 +00:00
export class CardMarketApi {
2019-11-21 12:09:51 +00:00
private AppToken: string;
private AppSecret: string;
private AccessToken: string;
private AccessSecret: string;
constructor() {
this.AppToken = process.env.APP_TOKEN;
this.AppSecret = process.env.APP_SECRET;
this.AccessToken = process.env.ACCESS_TOKEN;
this.AccessSecret = process.env.ACCESS_SECRET;
}
2019-11-23 15:20:58 +00:00
async request(
method: string,
path: string,
params: Record<string, any> | undefined,
options: any
): Promise<any> {
const oauth = {
2019-11-21 12:09:51 +00:00
realm: `${URI}${path}`,
consumer_key: this.AppToken,
consumer_secret: this.AppSecret,
token: this.AccessToken,
token_secret: this.AccessSecret
};
2019-11-23 15:20:58 +00:00
const uri = oauth.realm + (params ? `?${stringify(params)}` : "");
2019-11-21 12:09:51 +00:00
return new Promise((resolve, reject) => {
2019-11-23 15:20:58 +00:00
request(
2019-11-21 12:09:51 +00:00
{
2019-11-23 15:20:58 +00:00
method,
uri,
oauth,
...options
2019-11-21 12:09:51 +00:00
},
(error, response) => {
if (error) {
2019-11-23 15:20:58 +00:00
reject(error);
2019-11-21 12:09:51 +00:00
} else if (response.statusCode > 299) {
2019-11-23 15:20:58 +00:00
reject(
JSON.stringify({
statusCode: response.statusCode,
statusMessage: response.statusMessage,
statusBody: response.body
})
);
2019-11-21 12:09:51 +00:00
}
try {
resolve(JSON.parse(response.body));
} catch (error) {
reject(error);
}
}
);
});
}
2019-11-21 15:56:34 +00:00
2019-11-23 15:20:58 +00:00
async get(path: string, params?: Record<string, any>): Promise<any> {
return await this.request("GET", path, params, {});
}
async put(
path: string,
params?: Record<string, any>,
data?: string
): Promise<any> {
return await this.request(
"PUT",
path,
params,
data
? {
body: data
}
: {}
);
}
2019-11-21 15:56:34 +00:00
async getAllArticles(uid: string): Promise<Article[]> {
const perPage = 1000;
let start = 0;
let response;
let data: Article[] = [];
do {
response = await this.get(`/users/${uid}/articles`, {
start,
maxResults: perPage
});
data = data.concat(response.article as Article[]);
start += response.article.length;
} while (response.article.length == perPage);
return data;
}
2019-11-21 12:09:51 +00:00
}