-
Notifications
You must be signed in to change notification settings - Fork 0
/
bookMicroservice.js
94 lines (84 loc) · 2.26 KB
/
bookMicroservice.js
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
const sqlite3 = require('sqlite3').verbose();
const grpc = require('@grpc/grpc-js');
const protoLoader = require('@grpc/proto-loader');
const bookProtoPath = 'book.proto';
const bookProtoDefinition = protoLoader.loadSync(bookProtoPath, {
keepCase: true,
longs: String,
enums: String,
defaults: true,
oneofs: true,
});
const bookProto = grpc.loadPackageDefinition(bookProtoDefinition).book;
const db = new sqlite3.Database('./database.db');
db.run(`
CREATE TABLE IF NOT EXISTS books (
id INTEGER PRIMARY KEY,
title TEXT,
description TEXT
)
`);
const bookService = {
getBook: (call, callback) => {
const { book_id } = call.request;
db.get('SELECT * FROM books WHERE id = ?', [book_id], (err, row) => {
if (err) {
callback(err);
} else if (row) {
const book = {
id: row.id,
title: row.title,
description: row.description,
};
callback(null, { book });
} else {
callback(new Error('Booknot found'));
}
});
},
searchBooks: (call, callback) => {
db.all('SELECT * FROM books', (err, rows) => {
if (err) {
callback(err);
} else {
const books = rows.map((row) => ({
id: row.id,
title: row.title,
description: row.description,
}));
callback(null, { books });
}
});
},
CreateBook: (call, callback) => {
const { book_id, title, description } = call.request;
db.run(
'INSERT INTO books (id, title, description) VALUES (?, ?, ?)',
[book_id, title, description],
function (err) {
if (err) {
callback(err);
} else {
const book = {
id: book_id,
title,
description,
};
callback(null, { book });
}
}
);
},
};
const server = new grpc.Server();
server.addService(bookProto.BookService.service, bookService);
const port = 50051;
server.bindAsync(`0.0.0.0:${port}`, grpc.ServerCredentials.createInsecure(), (err, port) => {
if (err) {
console.error('Failed to bind server:', err);
return;
}
console.log(`Server is running on port ${port}`);
server.start();
});
console.log(`Book microservice running on port ${port}`);