@thedev132/yellowpages
Version:
HCB Yellow Pages for JS/TS
132 lines (130 loc) • 3.47 kB
JavaScript
// src/category.ts
var _Category = class _Category {
constructor({ code, key }) {
if (!code && !key) {
throw new Error("Either code or key must be provided");
}
this.code = code;
this.key = key;
}
static async initialize() {
if (this.categoriesByCode === null) {
const response = await fetch(
"https://raw.githubusercontent.com/hackclub/yellow_pages/main/lib/yellow_pages/categories.yaml"
);
const text = await response.text();
const yaml = await import("js-yaml");
const data = yaml.load(text);
this.categoriesByCode = Object.entries(data).reduce(
(acc, [code, obj]) => {
acc[code.toString()] = {
code: code.toString(),
...obj,
key: obj.key
};
return acc;
},
{}
);
this.categoriesByKey = Object.values(this.categoriesByCode).reduce(
(acc, category) => {
acc[category.key] = category;
return acc;
},
{}
);
}
}
static lookup(params) {
return new _Category(params);
}
get category() {
if (!_Category.categoriesByCode || !_Category.categoriesByKey) {
throw new Error(
"Categories not initialized. Call Category.initialize() first"
);
}
if (this.code) {
return _Category.categoriesByCode[this.code];
} else if (this.key) {
return _Category.categoriesByKey[this.key];
}
return void 0;
}
getCode() {
return this.category?.code;
}
getName() {
return this.category?.name;
}
getKey() {
return this.category?.key;
}
inDataset() {
return this.category !== void 0;
}
};
_Category.categoriesByCode = null;
_Category.categoriesByKey = null;
var Category = _Category;
// src/merchant.ts
var _Merchant = class _Merchant {
constructor({ networkId }) {
this.networkId = networkId;
}
static async initialize() {
if (this.merchants === null) {
const response = await fetch(
"https://raw.githubusercontent.com/hackclub/yellow_pages/main/lib/yellow_pages/merchants.yaml"
);
const text = await response.text();
const yaml = await import("js-yaml");
const data = yaml.load(text);
this.merchants = data.reduce((acc, merchant) => {
if (!merchant.name) return acc;
const filename = merchant.name.replace(/[ '-]/g, "").toLowerCase();
const iconUrl = `https://raw.githubusercontent.com/hackclub/yellow_pages/main/lib/assets/icons/${filename}.svg`;
merchant.network_ids.forEach((networkId) => {
acc[networkId] = {
name: merchant.name,
iconUrl
};
});
return acc;
}, {});
}
}
static lookup(params) {
return new _Merchant(params);
}
get merchant() {
if (!_Merchant.merchants) {
throw new Error(
"Merchants not initialized. Call Merchant.initialize() first"
);
}
return _Merchant.merchants[this.networkId];
}
getName() {
return this.merchant?.name;
}
async getIcon() {
if (!this.merchant?.iconUrl) return void 0;
try {
const response = await fetch(this.merchant.iconUrl);
if (!response.ok) return void 0;
return await response.text();
} catch {
return void 0;
}
}
inDataset() {
return this.merchant !== void 0;
}
};
_Merchant.merchants = null;
var Merchant = _Merchant;
export {
Category,
Merchant
};