@unchainedshop/plugins
Version:
Official plugin collection for the Unchained Engine with payment, delivery, and pricing adapters
44 lines (43 loc) • 1.91 kB
JavaScript
import { createLogger } from '@unchainedshop/logger';
import { ProductContractStandard } from '@unchainedshop/core-products';
import { systemLocale } from '@unchainedshop/utils';
const logger = createLogger('unchained:erc-metadata');
export async function ercMetadataHandler(request, context) {
try {
const { ROOT_URL = 'http://localhost:4010' } = process.env;
const { services, modules, locale, loaders, params } = context;
const url = new URL(request.url, ROOT_URL);
if (!url.pathname.toLowerCase().endsWith('.json')) {
throw new Error('Invalid ERC Metadata URI');
}
const { productId, localeOrTokenFilename, tokenFileName } = params;
const product = loaders
? await loaders.productLoader.load({ productId })
: await modules.products.findProduct({ productId });
const tokenSelector = {
contractAddress: product?.tokenization?.contractAddress,
};
if (product?.tokenization?.contractStandard !== ProductContractStandard.ERC721) {
tokenSelector.tokenSerialNumber = (tokenFileName || localeOrTokenFilename)
.toLowerCase()
.replace('.json', '');
}
const [token] = await modules.warehousing.findTokens(tokenSelector);
const resolvedLocale = tokenFileName
? new Intl.Locale(localeOrTokenFilename)
: locale || systemLocale;
const ercMetadata = await services.warehousing.ercMetadata({
product,
token,
locale: resolvedLocale,
});
if (!ercMetadata) {
return new Response(null, { status: 404 });
}
return Response.json(ercMetadata, { status: 200 });
}
catch (e) {
logger.error(e);
return Response.json({ name: e.name, code: e.code, message: e.message }, { status: 503 });
}
}