import { IDatabase, IServer } from "../interfaces"; import grpc from "@grpc/grpc-js"; const PROTO_PATH = "../proto/app.proto"; export default class GrpcServer implements IServer { server: any; db: IDatabase constructor(db: IDatabase) { this.db = db; const protoLoader = require("@grpc/proto-loader"); // Cannot convert this to an import const packageDefinition = protoLoader.loadSync(PROTO_PATH, { keepCase: true, longs: String, enums: String, defaults: true, oneofs: true, }); const { app } = grpc.loadPackageDefinition(packageDefinition); this.server.addService((app as any).App.service, { getRandomProduct: randomProduct, getAllProducts: allProducts, getProduct: product, getAllCategories: categories, getAllOrders: allOrders, getAllUserOrders: ordersByUser, getOrder: order, getUser: user, getAllUsers: users, postOrder: postOrder, patchAccountDetails: accountDetails, }); this.server = new grpc.Server(); } start() { this.server.bindAsync( "0.0.0.0:3001", grpc.ServerCredentials.createInsecure(), () => { console.log("App ready and listening on port 3001"); this.server.start(); }, ); } }; async function randomProduct(call, callback) { const randProd = await this.db.queryRandomProduct(); callback(null, randProd); } async function allProducts(call, callback) { const products = await this.db.queryAllProducts(); callback(null, { products }); } async function product(call, callback) { const { product_id } = call.request; const product = await this.db.queryProductById(product_id); callback(null, product); } async function categories(call, callback) { const categories = await this.db.queryAllCategories(); callback(null, { categories }); } async function allOrders(call, callback) { const orders = await this.db.queryAllOrders(); callback(null, { orders }); } async function ordersByUser(call, callback) { const { id } = call.request; const orders = await this.db.queryOrdersByUser(id); callback(null, { orders }); } async function order(call, callback) { const { order_id } = call.request; const order = await this.db.queryOrderById(order_id); callback(null, order); } async function user(call, callback) { const { id } = call.request; const user = await this.db.queryUserById(id); callback(null, user); } async function users(call, callback) { const users = await this.db.queryAllUsers(); callback(null, { users }); } async function postOrder(call, callback) { ///TODO: Implement this } async function accountDetails(call, callback) { const { id } = call.request; delete call.request.id; const user = await this.db.updateUser(id, call.request); callback(null, user); } /** * Starts an RPC server that receives requests for the Greeter service at the * sample server port */