forked from nishantwrp/microservices-example
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.ts
57 lines (46 loc) · 1.64 KB
/
server.ts
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
require('dotenv').config()
import * as grpc from "@grpc/grpc-js";
import * as protoLoader from "@grpc/proto-loader";
import { DatabaseClient } from "./database";
import { NewTodo, Todo, TodoCreator, TodoIdentifier, TodosList } from "./types";
import { grpcFunctionWrap } from "./utils";
const PORT = 3006;
const url = `0.0.0.0:${PORT}`;
const server = new grpc.Server();
const proto = grpc.loadPackageDefinition(protoLoader.loadSync("./protobuf/todo.proto"));
const dbClient = new DatabaseClient();
const getTodos = async (creator: TodoCreator): Promise<TodosList> => {
return {
todos: await dbClient.getTodosByUsername(creator.username),
};
}
const createTodo = async (newTodo: NewTodo): Promise<Todo> => {
return dbClient.createTodo(newTodo);
}
const getTodo = async (todoId: TodoIdentifier): Promise<Todo> => {
return dbClient.getTodoById(todoId);
}
const updateTodo = async (todo: Todo): Promise<Todo> => {
return dbClient.updateTodo(todo);
}
const deleteTodo = async (todoId: TodoIdentifier): Promise<void> => {
return dbClient.deleteTodo(todoId);
}
server.addService((proto.todo_service as any).TodoService.service, {
GetTodos: grpcFunctionWrap(getTodos),
CreateTodo: grpcFunctionWrap(createTodo),
GetTodo: grpcFunctionWrap(getTodo),
EditTodo: grpcFunctionWrap(updateTodo),
DeleteTodo: grpcFunctionWrap(deleteTodo),
} as any);
server.bindAsync(url, grpc.ServerCredentials.createInsecure(), (err, port) => {
if (err) {
throw err;
}
dbClient.initialize().then(() => {
server.start();
console.log(`Todo Service started on: ${url}`);
}, (err) => {
throw err;
});
});