Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
sagemathinc
GitHub Repository: sagemathinc/cocalc
Path: blob/master/src/packages/conat/service/time.ts
1452 views
1
/*
2
Time service -- tell me what time you think it is.
3
4
This is a global service that is run by hubs.
5
*/
6
7
import { createServiceClient, createServiceHandler } from "./typed";
8
import { getClient } from "@cocalc/conat/client";
9
10
interface TimeApi {
11
// time in ms since epoch, i.e., Date.now()
12
time: () => Promise<number>;
13
}
14
15
const SUBJECT = process.env.COCALC_TEST_MODE ? "time-test" : "time";
16
17
interface User {
18
account_id?: string;
19
project_id?: string;
20
}
21
22
function timeSubject({ account_id, project_id }: User) {
23
if (account_id) {
24
return `${SUBJECT}.account-${account_id}.api`;
25
} else if (project_id) {
26
return `${SUBJECT}.project-${project_id}.api`;
27
} else {
28
return `${SUBJECT}.hub.api`;
29
}
30
}
31
32
export function timeClient(user?: User) {
33
if (user == null) {
34
user = getClient();
35
}
36
const subject = timeSubject(user);
37
return createServiceClient<TimeApi>({
38
service: "time",
39
subject,
40
});
41
}
42
43
export async function createTimeService() {
44
return await createServiceHandler<TimeApi>({
45
service: "time",
46
subject: `${SUBJECT}.*.api`,
47
description: "Time service -- tell me what time you think it is.",
48
impl: { time: async () => Date.now() },
49
});
50
}
51
52