CachedData.ts
1 import fs from 'fs/promises' 2 import parser from 'csvtojson' 3 import pkgDir from 'pkg-dir' 4 import { CSVParseParam } from 'csvtojson/v2/Parameters' 5 6 const rootDirectory = pkgDir.sync( __dirname ) 7 const defaultParseOptions = { 8 delimiter: ',', 9 } 10 11 export interface CachedSkill { 12 id: number 13 level: number 14 line: string 15 } 16 17 export interface CachedItem { 18 itemId: number 19 } 20 21 export interface CachedNpc { 22 npcId: number 23 } 24 25 export let NpcReferenceIdToNpc : Record<string, CachedNpc> 26 export let SkillReferenceIdToSkill : Record<string, CachedSkill> 27 export let ItemReferenceIdToItem : Record<string, CachedItem> 28 29 async function getCsvFile( fileName: string, options : Partial<CSVParseParam> = defaultParseOptions ) : Promise<Array<unknown>> { 30 const fileContents = await fs.readFile( `${rootDirectory}/${fileName}` ) 31 return parser( options ).fromString( fileContents.toString() ) 32 } 33 34 export async function loadCaches() : Promise<void> { 35 const npcData = await getCsvFile( 'overrides/data/csv/npc/npcs.csv' ) 36 NpcReferenceIdToNpc = npcData.reduce( ( finalMap: Record<string, CachedNpc>, item: any ) : Record<string, CachedNpc> => { 37 const npcId = parseInt( item.id, 10 ) 38 if ( Number.isNaN( npcId ) ) { 39 throw new Error( `Unable to parse npcId for value=${item.id}` ) 40 } 41 42 finalMap[ item.referenceId ] = { 43 npcId 44 } 45 46 return finalMap 47 }, {} ) as Record<string, CachedNpc> 48 49 const skillReferences = await getCsvFile( 'overrides/data/csv/skillReferenceIds.csv' ) 50 SkillReferenceIdToSkill = skillReferences.reduce( ( finalMap: Record<string, CachedSkill>, item: any ): Record<string, CachedSkill> => { 51 const id = parseInt( item.skillId, 10 ) 52 if ( Number.isNaN( id ) ) { 53 throw new Error( `Unable to parse skill id for value=${item.skillId}` ) 54 } 55 56 const level = parseInt( item.skillLevel, 10 ) 57 if ( Number.isNaN( level ) ) { 58 throw new Error( `Unable to parse skill level for value=${item.skillLevel} and id=${item.skillId}` ) 59 } 60 61 finalMap[ item.name ] = { 62 id, 63 level, 64 line: `${id}-${level}` 65 } 66 67 return finalMap 68 }, {} ) as Record<string, CachedSkill> 69 70 const itemNames = await getCsvFile( 'overrides/data/csv/items/items.csv' ) 71 ItemReferenceIdToItem = itemNames.reduce( ( finalMap: Record<string, CachedItem>, item: any ) : Record<string, CachedItem> => { 72 const itemId = parseInt( item.itemId, 10 ) 73 if ( Number.isNaN( itemId ) ) { 74 throw new Error( `Unable to parse itemId for value=${item.itemId}` ) 75 } 76 77 finalMap[ item.referenceId ] = { 78 itemId 79 } 80 81 return finalMap 82 }, {} ) as Record<string, CachedItem> 83 }