72 lines
2.0 KiB
TypeScript
72 lines
2.0 KiB
TypeScript
import { MongoClient, Db, Collection } from 'mongodb'
|
|
import { Character } from './proto/character'
|
|
|
|
export class DatabaseService {
|
|
private readonly client: MongoClient
|
|
private readonly db: Db
|
|
private readonly characterCollection: Collection
|
|
|
|
constructor(databaseAddress: string, databaseName: string) {
|
|
this.client = new MongoClient(databaseAddress)
|
|
this.db = this.client.db(databaseName)
|
|
this.characterCollection = this.db.collection('characters')
|
|
}
|
|
|
|
insertCharacter(character: Character): Promise<Character> {
|
|
return this.characterCollection
|
|
.insertOne(character)
|
|
.then((insertResult) => {
|
|
console.log("Adding new character record:", insertResult)
|
|
return this.characterCollection.findOne({
|
|
_id: insertResult.insertedId,
|
|
})
|
|
})
|
|
.then(record => {
|
|
const character = recordToCharacter(record)
|
|
console.log(`New character result: \n _id: ${record._id}`, character)
|
|
return character
|
|
})
|
|
}
|
|
|
|
fetchCharactersForPlayer(playerName: string): Promise<Array<Character>> {
|
|
return this.characterCollection
|
|
.find({ playerName: playerName })
|
|
.toArray()
|
|
.then((results) => results.map(recordToCharacter))
|
|
}
|
|
|
|
fetchCharactersForCharacterName(playerName: string): Array<Character> {
|
|
return []
|
|
}
|
|
|
|
listCharacters(
|
|
playerName: string,
|
|
characterName: string,
|
|
): Promise<Array<Character>> {
|
|
let query = {}
|
|
|
|
if (playerName != '') query['playerName'] = playerName
|
|
if (characterName != '')
|
|
query['$or'] = [
|
|
{ characterName: characterName },
|
|
{ characterAlias: characterName},
|
|
]
|
|
|
|
return this.characterCollection
|
|
.find(query)
|
|
.toArray()
|
|
.then((results) => results.map(recordToCharacter))
|
|
}
|
|
}
|
|
|
|
function recordToCharacter(record): Character {
|
|
return {
|
|
playerName: record.playerName,
|
|
characterName: record.characterName,
|
|
characterAlias: record.characterAlias,
|
|
version: record.version,
|
|
sourceTable: record.sourceTable,
|
|
json: record.json,
|
|
}
|
|
}
|