-
-
Notifications
You must be signed in to change notification settings - Fork 10
/
main.ts
64 lines (51 loc) · 1.9 KB
/
main.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
58
59
60
61
62
63
64
import { readFileSync, writeFileSync, unlinkSync } from 'fs';
import { Types, unreachable } from '../generated/types';
const requestFilePath = '/tmp/request';
const responseFilePath = '/tmp/response';
const { SendEmailRequest, SendEmailResponse } = Types;
function writeToFiles(): void {
const requestMessage = {
to: 'typical@example.com',
subject: 'I love Typical!',
body: 'It makes serialization easy and safe.',
};
const responseMessage = {
error: 'Example error',
};
const requestArrayBuffer = SendEmailRequest.serialize(requestMessage);
writeFileSync(requestFilePath, Buffer.from(requestArrayBuffer));
const responseArrayBuffer = SendEmailResponse.serialize(responseMessage);
writeFileSync(responseFilePath, Buffer.from(responseArrayBuffer));
}
function readFromFiles(): void {
const requestFileContents = readFileSync(requestFilePath);
const requestMessage = SendEmailRequest.deserialize(requestFileContents);
if (requestMessage instanceof Error) {
throw requestMessage;
}
const responseFileContents = readFileSync(responseFilePath);
const responseMessage = SendEmailResponse.deserialize(responseFileContents);
if (responseMessage instanceof Error) {
throw responseMessage;
}
/* eslint-disable no-console -- Allow logging for this example. */
console.log('to:', requestMessage.to);
console.log('subject:', requestMessage.subject);
console.log('body:', requestMessage.body);
switch (responseMessage.$field) {
case 'success':
console.log('The email was sent!');
break;
case 'error':
console.log('An error occurred:', responseMessage.error);
break;
default:
return unreachable(responseMessage);
}
/* eslint-enable no-console -- Re-enable this rule. */
return undefined; // To satisfy ESLint's `consistent-return` rule
}
writeToFiles();
readFromFiles();
unlinkSync(requestFilePath);
unlinkSync(responseFilePath);