justtcg-js
Version:
The official JavaScript/TypeScript SDK for the JustTCG API.
214 lines (207 loc) • 7.43 kB
JavaScript
// src/core/http-client.ts
var HttpClient = class {
constructor(config) {
this.apiKey = config.apiKey;
this.baseUrl = config.baseUrl;
}
/**
* Performs a GET request to a given path.
* @param path The endpoint path (e.g., '/games').
* @param params Optional query parameters.
* @returns The JSON response from the API.
*/
async get(path, params) {
const url = new URL(`${this.baseUrl}${path}`);
if (params) {
Object.entries(params).forEach(([key, value]) => {
if (value !== void 0 && value !== null) {
url.searchParams.append(key, String(value));
}
});
}
const response = await fetch(url.toString(), {
method: "GET",
headers: this.getHeaders()
});
if (!response.ok) {
const errorBody = await response.json();
throw new Error(errorBody.error || "An API error occurred");
}
return response.json();
}
/**
* Performs a POST request to a given path.
* @param path The endpoint path (e.g., '/cards').
* @param body The JSON body for the request.
* @returns The JSON response from the API.
*/
async post(path, body) {
const url = new URL(`${this.baseUrl}${path}`);
const stringifiedBody = body.map((item) => {
const stringifiedItem = {};
if (item.tcgplayerId) stringifiedItem.tcgplayerId = item.tcgplayerId;
if (item.tcgplayerSkuId) stringifiedItem.tcgplayerSkuId = item.tcgplayerSkuId;
if (item.cardId) stringifiedItem.cardId = item.cardId;
if (item.variantId) stringifiedItem.variantId = item.variantId;
if (item.scryfallId) stringifiedItem.scryfallId = item.scryfallId;
if (item.mtgjsonId) stringifiedItem.mtgjsonId = item.mtgjsonId;
if (item.printing) stringifiedItem.printing = Array.isArray(item.printing) ? item.printing.join(",") : item.printing;
if (item.condition) stringifiedItem.condition = Array.isArray(item.condition) ? item.condition.join(",") : item.condition;
if (item.include_price_history !== void 0) stringifiedItem.include_price_history = String(item.include_price_history);
if (item.include_statistics) stringifiedItem.include_statistics = Array.isArray(item.include_statistics) ? item.include_statistics.join(",") : item.include_statistics;
if (item.updated_after !== void 0) stringifiedItem.updated_after = String(item.updated_after);
return stringifiedItem;
});
console.log(stringifiedBody);
const response = await fetch(url.toString(), {
method: "POST",
headers: this.getHeaders(),
body: JSON.stringify(stringifiedBody)
});
if (!response.ok) {
const errorBody = await response.json();
throw new Error(errorBody.error || "An API error occurred");
}
return response.json();
}
getHeaders() {
return {
"Content-Type": "application/json",
"x-api-key": this.apiKey
// Add the API key header
};
}
};
// src/core/response-handler.ts
function handleResponse(rawResponse) {
const usage = {
apiRequestLimit: rawResponse._metadata.apiRequestLimit,
apiDailyLimit: rawResponse._metadata.apiDailyLimit,
apiRateLimit: rawResponse._metadata.apiRateLimit,
apiRequestsUsed: rawResponse._metadata.apiRequestsUsed,
apiDailyRequestsUsed: rawResponse._metadata.apiDailyRequestsUsed,
apiRequestsRemaining: rawResponse._metadata.apiRequestsRemaining,
apiDailyRequestsRemaining: rawResponse._metadata.apiDailyRequestsRemaining,
apiPlan: rawResponse._metadata.apiPlan
};
const pagination = rawResponse.meta ? {
total: rawResponse.meta.total,
limit: rawResponse.meta.limit,
offset: rawResponse.meta.offset,
hasMore: rawResponse.meta.hasMore
} : void 0;
return {
data: rawResponse.data,
pagination,
usage,
...rawResponse.error && { error: rawResponse.error },
...rawResponse.code && { code: rawResponse.code }
};
}
// src/v1/resources/base.ts
var BaseResource = class {
constructor(httpClient, pathPrefix) {
this.httpClient = httpClient;
this.pathPrefix = pathPrefix;
}
async _get(path, params) {
if (params && "query" in params && typeof params.query === "string") {
params.q = params.query;
delete params.query;
}
return this.httpClient.get(`${this.pathPrefix}${path}`, params);
}
async _post(path, body) {
return this.httpClient.post(`${this.pathPrefix}${path}`, body);
}
};
// src/v1/resources/cards.ts
var CardsResource = class extends BaseResource {
/**
* Retrieves a paginated list of cards based on a flexible set of query parameters.
* @param params Parameters for searching, filtering, and paginating cards.
* @returns A Promise resolving to the JustTCG API response containing an array of Card objects.
*/
async get(params) {
const rawResponse = await this._get("/cards", params);
return handleResponse(rawResponse);
}
/**
* Retrieves a list of cards based on a batch of specific identifiers.
* @param items An array of objects, each identifying a card to look up.
* @returns A Promise resolving to the JustTCG API response containing an array of the requested Card objects.
*/
async getByBatch(items) {
const rawResponse = await this._post("/cards", items);
return handleResponse(rawResponse);
}
/**
* A convenience method to search for cards by a query string.
* This is a wrapper around the more flexible `get` method.
* @param query A search query for the card's name.
* @param options Optional parameters to filter or paginate the search results.
* @returns A Promise resolving to the JustTCG API response containing an array of Card objects.
*/
async search(query, options) {
const params = {
query,
...options
};
return this.get(params);
}
};
// src/v1/resources/games.ts
var GamesResource = class extends BaseResource {
/**
* Retrieves a list of all supported games.
* @returns A JustTCG API response containing an array of Game objects.
*/
async list() {
const rawResponse = await this._get("/games");
return handleResponse(rawResponse);
}
};
// src/v1/resources/sets.ts
var SetsResource = class extends BaseResource {
/**
* Retrieves a paginated list of sets, optionally filtered by game.
* @param params Optional parameters to filter the list of sets.
* @returns A JustTCG API response containing an array of Set objects.
*/
async list(params) {
const rawResponse = await this._get("/sets", params);
return handleResponse(rawResponse);
}
};
// src/v1/index.ts
var V1Client = class {
constructor(httpClient) {
const pathPrefix = "/v1";
this.games = new GamesResource(httpClient, pathPrefix);
this.sets = new SetsResource(httpClient, pathPrefix);
this.cards = new CardsResource(httpClient, pathPrefix);
}
};
// src/index.ts
var API_BASE_URL = "https://api.justtcg.com";
var JustTCG = class {
/**
* Creates an instance of the JustTCG client.
* @param config Configuration options for the client.
*/
constructor(config = {}) {
const apiKey = config.apiKey ?? process.env.JUSTTCG_API_KEY;
if (!apiKey) {
throw new Error("Authentication error: API key is missing.");
}
this.httpClient = new HttpClient({
apiKey,
baseUrl: API_BASE_URL
});
this.v1 = new V1Client(this.httpClient);
}
};
export {
JustTCG
};
//# sourceMappingURL=index.mjs.map