-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathdemo.ts
113 lines (103 loc) · 2.78 KB
/
demo.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
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
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
import { asJSON, asMaybe, asObject, asString, uncleaner } from 'cleaners'
import fetch from 'node-fetch'
import { base64 } from 'rfc4648'
import {
asDeviceUpdatePayload,
asLoginUpdatePayload,
asPushRequestBody
} from '../src/types/pushApiTypes'
// We are going to use uncleaners to type-check our payloads:
const wasPushRequestBody = uncleaner(asPushRequestBody)
const wasDeviceUpdatePayload = uncleaner(asDeviceUpdatePayload)
const wasLoginUpdatePayload = uncleaner(asLoginUpdatePayload)
/**
* Failed requests usually return this as their body.
*/
const asErrorBody = asJSON(
asObject({
error: asString
})
)
const server = 'http://127.0.0.1:8001'
const apiKey = 'demo-api-key'
const deviceId = 'example-device'
// Non-existing account for demo purposes:
const loginId = base64.parse('O8vz73AA76MejE3bCh6t6F2Lr7TLfQVB2+Tm0sC35tc=')
/**
* All push server HTTP methods use "POST" with JSON.
*/
async function postJson(uri: string, body: unknown): Promise<unknown> {
console.log(JSON.stringify(body, null, 1))
const response = await fetch(uri, {
body: JSON.stringify(body),
headers: {
accept: 'application/json',
'content-type': 'application/json'
},
method: 'POST'
})
if (!response.ok) {
const error = asMaybe(asErrorBody)(await response.text())
let message = `POST ${uri} returned ${response.status}`
if (error != null) message += `: ${error.error}`
throw new Error(message)
}
return await response.json()
}
async function main(): Promise<void> {
// Create a device:
await postJson(
`${server}/v2/device/update/`,
wasPushRequestBody({
apiKey,
deviceId,
data: wasDeviceUpdatePayload({ loginIds: [loginId] })
})
)
console.log(`Updated device "${deviceId}"`)
// Grab the device status:
console.log(
await postJson(
`${server}/v2/device/`,
wasPushRequestBody({ apiKey, deviceId })
)
)
// Subscribe the user to a price change:
await postJson(
`${server}/v2/login/update/`,
wasPushRequestBody({
apiKey,
deviceId,
loginId,
data: wasLoginUpdatePayload({
createEvents: [
{
eventId: 'demo-event',
pushMessage: {
title: 'Example title',
body: 'Example body',
data: { what: 'happened' }
},
trigger: {
type: 'price-level',
currencyPair: 'BTC-USD',
aboveRate: 50000
}
}
]
})
})
)
console.log(`Updated login "${base64.stringify(loginId)}"`)
// Grab the login status:
console.log(
await postJson(
`${server}/v2/login/`,
wasPushRequestBody({ apiKey, deviceId, loginId })
)
)
}
main().catch(error => {
console.error(String(error))
process.exitCode = 1
})