Newer
Older
import { IDatabase, IServer } from "../interfaces";
import grpc from "@grpc/grpc-js";
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,
});
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
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
*/