This repository was archived by the owner on Mar 11, 2025. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathindex.ts
More file actions
85 lines (77 loc) · 3.09 KB
/
index.ts
File metadata and controls
85 lines (77 loc) · 3.09 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
import {AsklessServer} from "../../src";
import {MessageModel} from "./message-model";
import {MessageEntity} from "./message-entity";
const server = new AsklessServer<"blue" | "green">();
const isProduction = false;
const allMessages = [];
server.init({
sendInternalErrorsToClient: !isProduction,
authenticate: (credential, accept, reject) => {
accept.asAuthenticatedUser({ userId: credential["myColor"] });
// fake authentication, please check [TODO] for a real authentication example or the docs
},
debugLogs: !isProduction,
wsOptions : {
port : 3000
},
});
const readRouteInRealtime = server.addRoute.forAuthenticatedUsers.read<MessageEntity[]>({
route: 'message',
handleRead: async (context) => {
context.successCallback(allMessages);
},
onClientStartsListening: async (context) => {
readRouteInRealtime.notifyChanges({
where: (whereContext) => {
return whereContext.userId == context.userId;
},
handleReadOverride: (readContext) => {
readContext.successCallback(
[ //Send array of messages with one item only
new MessageEntity( //Send array of messages with one item only
/** text */'server said: Welcome to the simple-chat-ts screen!',
/** origin */ context.userId,
/** createdAt */ new Date(),
)
]
);
},
});
},
onClientStopsListening: async (context) => {
readRouteInRealtime.notifyChanges({
where: (whereContext) => whereContext.userId != context.userId,
handleReadOverride: readContext => {
readContext.successCallback([
new MessageEntity( //Send array of messages with one item only
/** text */'server said: '+context.userId+' has been disconnected from the chat and didn\'t connect again',
/** origin */ readContext.userId,
/** createdAt */ new Date(),
)
])
}
});
},
toOutput: entityList => {
return MessageModel.fromEntityList(entityList).map(model => model.toOutput());
}
});
server.addRoute.forAuthenticatedUsers.create<MessageEntity>({
route: 'message',
handleCreate: (async (context) => {
const message:MessageEntity = new MessageEntity(context.body.text, context.userId, new Date());
allMessages.push(message);
//notify the route where client receives in realtime
readRouteInRealtime.notifyChanges({
handleReadOverride: readContext => {
readContext.successCallback([ //Send array of messages with one item only
message
]);
}
});
context.successCallback(message);
}),
toOutput: entity => MessageModel.fromEntity(entity).toOutput(),
});
server.start();
console.log('my local server url: '+server.localUrl);