-
Notifications
You must be signed in to change notification settings - Fork 1
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
William/v2 prototype #40
base: master
Are you sure you want to change the base?
Changes from all commits
4cc7aaa
caf06b9
0121844
94a54e6
32b732a
615dddd
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,112 @@ | ||
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 apiKey = 'demo-api-key' | ||
const deviceId = 'example-device' | ||
const loginId = base64.parse('EE+tBb5wM63qwCDVidzwUQThH9ekCSfpUuTQYujSmY8=') | ||
|
||
/** | ||
* All push server HTTP methods use "POST" with JSON. | ||
*/ | ||
async function postJson(uri: string, body: unknown): Promise<unknown> { | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. I wish I had noticed this function early. I like it and would prefer to use it in the GUI (if not now, then later). |
||
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( | ||
'http://127.0.0.1:8001/v2/device/update/', | ||
wasPushRequestBody({ | ||
apiKey, | ||
deviceId, | ||
data: wasDeviceUpdatePayload({ loginIds: [loginId] }) | ||
}) | ||
) | ||
Comment on lines
+53
to
+60
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. This would be the isomorphic dream: import pushServer from 'https://push.edge.app/api'
pushServer.device.update({ apiKey, deviceId, data: { loginIds: [loginId] } }) This magic would be enabled with URL imports in our client-side environments (something Deno or Bun enables) and using a special HTTP server framework (ala serverlet) which could syndicate a public API derived from the defined routes at the TL;DR: Another thing to add to the side-project/experiment list. |
||
console.log(`Updated device "${deviceId}"`) | ||
|
||
// Grab the device status: | ||
console.log( | ||
await postJson( | ||
'http://127.0.0.1:8001/v2/device/', | ||
wasPushRequestBody({ apiKey, deviceId }) | ||
) | ||
) | ||
|
||
// Subscribe the user to a price change: | ||
await postJson( | ||
'http://127.0.0.1:8001/v2/login/update/', | ||
wasPushRequestBody({ | ||
apiKey, | ||
deviceId, | ||
loginId, | ||
data: wasLoginUpdatePayload({ | ||
createEvents: [ | ||
{ | ||
eventId: 'demo-event', | ||
pushMessage: { | ||
title: 'Example title', | ||
body: 'Example body', | ||
data: { what: 'happened' } | ||
}, | ||
recurring: false, | ||
trigger: { | ||
type: 'price-level', | ||
currencyPair: 'BTC-USD', | ||
aboveRate: 50000 | ||
} | ||
} | ||
] | ||
}) | ||
}) | ||
) | ||
console.log(`Updated login "${base64.stringify(loginId)}"`) | ||
|
||
// Grab the login status: | ||
console.log( | ||
await postJson( | ||
'http://127.0.0.1:8001/v2/login/', | ||
wasPushRequestBody({ apiKey, deviceId, loginId }) | ||
) | ||
) | ||
} | ||
|
||
main().catch(error => { | ||
console.error(String(error)) | ||
process.exitCode = 1 | ||
}) |
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,173 @@ | ||
import { | ||
asArray, | ||
asDate, | ||
asObject, | ||
asOptional, | ||
asString, | ||
uncleaner | ||
} from 'cleaners' | ||
import { | ||
asCouchDoc, | ||
asMaybeConflictError, | ||
asMaybeNotFoundError, | ||
DatabaseSetup, | ||
makeJsDesign | ||
} from 'edge-server-tools' | ||
import { ServerScope } from 'nano' | ||
import { base64 } from 'rfc4648' | ||
|
||
import { asBase64 } from '../types/pushCleaners' | ||
import { Device } from '../types/pushTypes' | ||
|
||
/** | ||
* A device returned from the database. | ||
* Mutate the `device` object, then call `save` to commit the changes. | ||
*/ | ||
export interface DeviceRow { | ||
device: Device | ||
save: () => Promise<void> | ||
} | ||
|
||
/** | ||
* An API key, as stored in Couch. | ||
*/ | ||
export const asCouchDevice = asCouchDoc<Omit<Device, 'deviceId'>>( | ||
asObject({ | ||
created: asDate, | ||
|
||
// Status: | ||
apiKey: asOptional(asString), | ||
deviceToken: asOptional(asString), | ||
loginIds: asArray(asBase64), | ||
visited: asDate | ||
}) | ||
) | ||
const wasCouchDevice = uncleaner(asCouchDevice) | ||
type CouchDevice = ReturnType<typeof asCouchDevice> | ||
|
||
/** | ||
* Looks up devices that contain a particular login. | ||
*/ | ||
const loginIdDesign = makeJsDesign('loginId', ({ emit }) => ({ | ||
map: function (doc) { | ||
for (let i = 0; i < doc.loginIds.length; ++i) { | ||
emit(doc.loginIds[i], null) | ||
} | ||
} | ||
})) | ||
|
||
export const couchDevicesSetup: DatabaseSetup = { | ||
name: 'push-devices', | ||
documents: { | ||
'_design/loginId': loginIdDesign | ||
} | ||
} | ||
|
||
/** | ||
* Looks up a device by its id. | ||
* If the device does not exist in the database, creates a fresh row. | ||
*/ | ||
export async function getDeviceById( | ||
connection: ServerScope, | ||
deviceId: string, | ||
date: Date | ||
): Promise<DeviceRow> { | ||
const db = connection.use(couchDevicesSetup.name) | ||
const raw = await db.get(deviceId).catch(error => { | ||
if (asMaybeNotFoundError(error) != null) return | ||
throw error | ||
}) | ||
|
||
if (raw == null) { | ||
return makeDeviceRow(connection, { | ||
created: date, | ||
deviceId, | ||
apiKey: undefined, | ||
deviceToken: undefined, | ||
loginIds: [], | ||
visited: date | ||
}) | ||
} | ||
const clean = asCouchDevice(raw) | ||
return makeDeviceRow( | ||
connection, | ||
{ ...clean.doc, deviceId: clean.id }, | ||
clean.rev | ||
) | ||
} | ||
|
||
/** | ||
* Finds all the devices that have logged into this account. | ||
*/ | ||
export async function getDevicesByLoginId( | ||
connection: ServerScope, | ||
loginId: Uint8Array | ||
): Promise<DeviceRow[]> { | ||
const db = connection.use(couchDevicesSetup.name) | ||
const response = await db.view('loginId', 'loginId', { | ||
include_docs: true, | ||
key: base64.stringify(loginId) | ||
}) | ||
return response.rows.map(row => { | ||
const clean = asCouchDevice(row.doc) | ||
return makeDeviceRow( | ||
connection, | ||
{ ...clean.doc, deviceId: clean.id }, | ||
clean.rev | ||
) | ||
}) | ||
} | ||
|
||
function makeDeviceRow( | ||
connection: ServerScope, | ||
device: Device, | ||
rev?: string | ||
): DeviceRow { | ||
const db = connection.db.use(couchDevicesSetup.name) | ||
let base = { ...device } | ||
|
||
return { | ||
device, | ||
|
||
async save(): Promise<void> { | ||
while (true) { | ||
// Write to the database: | ||
const doc: CouchDevice = { | ||
doc: device, | ||
id: device.deviceId, | ||
rev | ||
} | ||
const response = await db.insert(wasCouchDevice(doc)).catch(error => { | ||
if (asMaybeConflictError(error) == null) throw error | ||
}) | ||
|
||
// If that worked, the merged document is now the latest: | ||
if (response?.ok === true) { | ||
base = { ...device } | ||
rev = doc.rev | ||
return | ||
} | ||
|
||
// Something went wrong, so grab the latest remote document: | ||
const raw = await db.get(device.deviceId) | ||
const clean = asCouchDevice(raw) | ||
rev = clean.rev | ||
const remote = clean.doc | ||
|
||
// If we don't have local edits, take the remote field: | ||
if (device.apiKey === base.apiKey) { | ||
device.apiKey = remote.apiKey | ||
} | ||
if (device.deviceToken === base.deviceToken) { | ||
device.deviceToken = remote.deviceToken | ||
} | ||
if (device.loginIds === base.loginIds) { | ||
device.loginIds = remote.loginIds | ||
} | ||
if (remote.visited > device.visited) { | ||
device.visited = remote.visited | ||
} | ||
} | ||
} | ||
} | ||
} |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Is this loginId a test loginId?