48 lines
1.3 KiB
TypeScript
48 lines
1.3 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(insertResult)
|
|
return this.characterCollection.findOne({
|
|
_id: insertResult.insertedId,
|
|
})
|
|
})
|
|
.then(recordToCharacter)
|
|
}
|
|
|
|
fetchCharactersForPlayer(playerName: string): Promise<Array<Character>> {
|
|
return this.characterCollection
|
|
.find({ playerName: playerName })
|
|
.toArray()
|
|
.then((results) =>
|
|
results.map(recordToCharacter),
|
|
)
|
|
}
|
|
|
|
fetchCharactersForCharacterName(playerName: string): Array<Character> {
|
|
return []
|
|
}
|
|
}
|
|
|
|
function recordToCharacter(record): Character {
|
|
return {
|
|
playerName: record.playerName,
|
|
characterName: record.characterName,
|
|
characterAlias: record.characterAlias,
|
|
}
|
|
}
|