Get it to store data from grpc calls.

This commit is contained in:
iamBadgers
2025-06-13 21:17:35 -07:00
parent 1bcaedc293
commit 7230d526e0
8 changed files with 104 additions and 430 deletions

View File

@@ -1,6 +1,7 @@
import { Server } from '@grpc/grpc-js'
import { Server, ServerUnaryCall, sendUnaryData } from '@grpc/grpc-js'
import { ReflectionService } from '@grpc/reflection'
import { loadSync } from '@grpc/proto-loader'
import { MongoClient, Collection, Db } from 'mongodb'
import {
Character,
@@ -13,28 +14,66 @@ import {
ICharacterManager,
} from './proto/character.grpc-server'
export function initCharacterService(server: Server) {
server.addService(characterManagerDefinition, CharacterManagerService)
export class CharacterService {
reflectionService: ReflectionService
characterManager: ICharacterManager
new ReflectionService(loadSync('./src/proto/character.proto')).addToServer(
server,
)
}
mongoClient: MongoClient
db: Db
characterCollection: Collection
const CharacterManagerService: ICharacterManager = {
createCharacter: (request: CreateCharacterRequest): Character => {
return {
constructor(mongoClient: MongoClient, dbName: string) {
this.reflectionService = new ReflectionService(
loadSync('./src/proto/character.proto'),
)
this.characterManager = {
createCharacter: this.createCharacterCall.bind(this),
getCharacter: this.getCharacterCall.bind(this),
}
this.mongoClient = mongoClient
this.db = this.mongoClient.db(dbName)
this.characterCollection = this.db.collection('Characters')
}
addToServer(server: Server) {
server.addService(characterManagerDefinition, this.characterManager)
this.reflectionService.addToServer(server)
}
async createCharacterCall(
call: ServerUnaryCall<CreateCharacterRequest, Character>,
callback: sendUnaryData<Character>,
) {
let newCharacter = await this.characterCollection
.insertOne(call.request.characterData)
.then((insertResult) => {
console.log(insertResult)
return this.characterCollection.findOne({
_id: insertResult.insertedId,
})
})
console.log(newCharacter)
callback(null, {
playerName: newCharacter.playerName,
characterName: newCharacter.characterName,
characterAlias: newCharacter.characterAlias,
})
}
getCharacterCall(
call: ServerUnaryCall<GetCharacterRequest, Character>,
callback: sendUnaryData<Character>,
) {
callback(null, {
playerName: 'test player',
characterName: 'test character',
characterAlias: ['test alias'],
}
},
getCharacter: (request: GetCharacterRequest): Character => {
return {
playerName: 'test player',
characterName: 'test character',
characterAlias: ['test alias'],
}
},
})
}
}