nitro-converter/src/converters/ProductDataConverter.ts

73 lines
2.2 KiB
TypeScript
Raw Normal View History

2021-08-19 04:02:25 -04:00
import { writeFile } from 'fs/promises';
2021-12-22 03:45:09 -05:00
import ora from 'ora';
2021-08-19 04:02:25 -04:00
import { singleton } from 'tsyringe';
2021-12-22 03:45:09 -05:00
import { Configuration, FileUtilities, IConverter, IProductData } from '../common';
2021-08-19 04:02:25 -04:00
@singleton()
2021-12-22 03:45:09 -05:00
export class ProductDataConverter implements IConverter
2021-08-19 04:02:25 -04:00
{
public productData: IProductData = null;
constructor(
private readonly _configuration: Configuration)
2021-12-22 03:45:09 -05:00
{}
2021-08-19 04:02:25 -04:00
public async convertAsync(args: string[] = []): Promise<void>
{
const now = Date.now();
const spinner = ora('Preparing ProductData').start();
const url = this._configuration.getValue('productdata.load.url');
const content = await FileUtilities.readFileAsString(url);
2021-12-22 03:45:09 -05:00
this.productData = ((!content.startsWith('{')) ? await this.mapText2JSON(content) : JSON.parse(content));
2021-08-19 04:02:25 -04:00
2021-12-22 03:45:09 -05:00
const directory = await FileUtilities.getDirectory('./assets/gamedata');
2021-08-19 04:02:25 -04:00
const path = directory.path + '/ProductData.json';
await writeFile(path, JSON.stringify(this.productData), 'utf8');
2021-12-22 03:45:09 -05:00
spinner.succeed(`ProductData: Finished in ${ Date.now() - now }ms`);
2021-08-19 04:02:25 -04:00
}
private async mapText2JSON(text: string): Promise<IProductData>
{
if(!text) return null;
const output: IProductData = {
productdata: {
product: []
}
};
text = text.replace(/"{1,}/g, '');
const parts = text.split(/\n\r{1,}|\n{1,}|\r{1,}/mg);
for(const part of parts)
{
const set = part.match(/\[+?((.)*?)\]/g);
if(set)
{
for(const entry of set)
{
let value = entry.replace(/\[{1,}/mg, '');
value = entry.replace(/\]{1,}/mg, '');
value = value.replace('[[', '');
value = value.replace('[', '');
const pieces = value.split(',');
const code = pieces.shift();
const name = pieces.shift();
const description = pieces.join(',');
output.productdata.product.push({ code, name, description });
}
}
}
return output;
}
}