-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.ts
More file actions
158 lines (145 loc) · 4.26 KB
/
index.ts
File metadata and controls
158 lines (145 loc) · 4.26 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
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
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
import grpc from '@grpc/grpc-js';
import protoLoader from '@grpc/proto-loader';
import { MongoClient, ObjectId } from 'mongodb';
const packageDefinition = protoLoader.loadSync('catalog.proto', {});
const catalogProto = grpc.loadPackageDefinition(packageDefinition).catalog;
const mongoURI = process.env.DATABASE_URI || 'mongodb://localhost:27017';
const dbName = process.env.DATABASE_NAME;
let db;
const client = new MongoClient(mongoURI);
async function connectToMongo() {
try {
await client.connect();
db = client.db(dbName);
console.log('Connected to Mongodb');
} catch (err) {
console.error('Error connecting to MongoDB:', err);
}
}
const getProduct = async (call, callback) => {
try {
const { id } = call.request;
const product = await db.collection('products').findOne(
{ _id: ObjectId.createFromHexString(id) },
{ projection: { _id: 0, id: { $toString: "$_id" }, name: 1, description: 1 } }
);
if (!product) {
callback({
code: grpc.status.NOT_FOUND,
message: 'Product not found',
});
return;
}
callback(null, product);
} catch (err) {
console.error('Error searching product:', err);
callback({
code: grpc.status.INTERNAL,
message: 'Internal server error',
});
}
};
const getProducts = async (call, callback) => {
try {
const products = await db.collection('products').find(
{},
{ projection: { _id: 0, id: { $toString: "$_id" }, name: 1, description: 1 } }
).toArray();
callback(null, { products });
} catch (err) {
console.error('Error fetching products:', err);
callback({
code: grpc.status.INTERNAL,
message: 'Internal server error',
});
}
};
const createProduct = async (call, callback) => {
try {
const { name, description } = call.request;
const result = await db.collection('products').insertOne({ name, description });
callback(null, {
id: result.insertedId,
name,
description,
});
console.log('Product created:', result);
} catch (err) {
console.error('Error creating product:', err);
callback({
code: grpc.status.INTERNAL,
message: 'Internal server error',
});
}
};
const deleteProduct = async (call, callback) => {
try {
const { id } = call.request;
const result = await db.collection('products').deleteOne({ _id: ObjectId.createFromHexString(id) });
if (result.deletedCount === 0) {
callback({
code: grpc.status.NOT_FOUND,
message: 'Product not found',
});
return;
}
callback(null, {});
console.log('Product deleted:', result);
} catch (err) {
console.error('Error deleting product:', err);
callback({
code: grpc.status.INTERNAL,
message: 'Internal server error',
});
}
};
const updateProduct = async (call, callback) => {
try {
const { id, name, description } = call.request;
const result = await db.collection('products').updateOne(
{ _id: ObjectId.createFromHexString(id) },
{ $set: { name, description } }
);
if (result.matchedCount === 0) {
callback({
code: grpc.status.NOT_FOUND,
message: 'Product not found',
});
return;
}
const updatedProduct = await db.collection('products').findOne(
{ _id: ObjectId.createFromHexString(id) },
{ projection: { _id: 0, id: { $toString: "$_id" }, name: 1, description: 1 } }
);
callback(null, updatedProduct);
console.log('Product updated:', result);
} catch (err) {
console.error('Error updating product:', err);
callback({
code: grpc.status.INTERNAL,
message: 'Internal server error',
});
}
};
function startServer() {
const server = new grpc.Server();
server.addService(catalogProto.CatalogService.service, {
GetProduct: getProduct,
GetProducts: getProducts,
CreateProduct: createProduct,
DeleteProduct: deleteProduct,
UpdateProduct: updateProduct,
});
const port = process.env.PORT || '50051';
server.bindAsync(`0.0.0.0:${port}`, grpc.ServerCredentials.createInsecure(), (err, bindPort) => {
if (err) {
console.error('Error starting gRPC:', err);
return;
}
console.log(`gRPC listening at: ${bindPort}`);
});
}
(async () => {
await connectToMongo();
startServer();
})();