Skip to content

Create db cleanups for models #34

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

Open
wants to merge 8 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
102 changes: 102 additions & 0 deletions src/db/couchDevices.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,102 @@
import { asNumber, asObject, asOptional, asString, uncleaner } from 'cleaners'
import {
asCouchDoc,
asMaybeConflictError,
asMaybeNotFoundError,
DatabaseSetup
} from 'edge-server-tools'
import { ServerScope } from 'nano'

import { DeviceRow } from '../types/dbTypes'
import { Device } from '../types/pushTypes'

export const asCouchDevice = asCouchDoc<Omit<Device, 'deviceId'>>(
asObject({
appId: asString,
tokenId: asOptional(asString),
deviceDescription: asString,
osType: asString,
edgeVersion: asString,
edgeBuildNumber: asNumber
})
)
const wasCouchDevice = uncleaner(asCouchDevice)
type CouchDevice = ReturnType<typeof asCouchDevice>
export const devicesSetup: DatabaseSetup = { name: 'db_devices' }

export const fetchDevice = async (
connection: ServerScope,
deviceId: string
): Promise<Device | null> => {
const db = connection.db.use(devicesSetup.name)
const raw = await db.get(deviceId).catch(error => {
if (asMaybeNotFoundError(error) != null) return
throw error
})
if (raw == null) return null
const deviceDoc = asCouchDevice(raw)
return unpackDevice(deviceDoc)
}

export const saveDeviceToDB = async (
connection: ServerScope,
device: Device
): Promise<void> => {
const db = connection.db.use(devicesSetup.name)

const raw = await db.get(device.deviceId).catch(error => {
if (asMaybeNotFoundError(error) != null) return
throw error
})
if (raw == null) return
const { save } = makeDeviceRow(connection, raw)
await save()
}

export const makeDeviceRow = (
connection: ServerScope,
raw: unknown
): DeviceRow => {
const db = connection.db.use(devicesSetup.name)
let base = asCouchDevice(raw)
const device: Device = { ...base.doc, deviceId: base.id }
return {
device,
async save() {
let remote = base
while (true) {
// Write to the database:
const doc: CouchDevice = {
doc: { ...device },
id: remote.id,
rev: remote.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 = doc
return
}

// Something went wrong, so grab the latest remote document:
const raw = await db.get(device.deviceId)
remote = asCouchDevice(raw)
}
}
}
}

export const unpackDevice = (doc: CouchDevice): Device => {
return { ...doc.doc, deviceId: doc.id }
}

export const packDevice = (device: Device): CouchDevice => {
const { deviceId, ...doc } = device
return {
id: deviceId,
doc: doc
}
}
14 changes: 4 additions & 10 deletions src/db/couchSetup.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,23 +7,17 @@ import { ServerScope } from 'nano'

import { serverConfig } from '../serverConfig'
import { couchApiKeysSetup } from './couchApiKeys'
import { devicesSetup } from './couchDevices'
import { settingsSetup, syncedReplicators } from './couchSettings'
import { usersSetup } from './couchUsers'

// ---------------------------------------------------------------------------
// Databases
// ---------------------------------------------------------------------------

const thresholdsSetup: DatabaseSetup = { name: 'db_currency_thresholds' }
export const apiKeysSetup: DatabaseSetup = { name: 'db_api_keys' }

const devicesSetup: DatabaseSetup = { name: 'db_devices' }

const usersSetup: DatabaseSetup = {
name: 'db_user_settings'
// documents: {
// '_design/filter': makeJsDesign('by-currency', ?),
// '_design/map': makeJsDesign('currency-codes', ?)
// }
}
export const thresholdsSetup: DatabaseSetup = { name: 'db_currency_thresholds' }

// ---------------------------------------------------------------------------
// Setup routine
Expand Down
202 changes: 202 additions & 0 deletions src/db/couchUsers.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,202 @@
import {
asBoolean,
asMap,
asObject,
asOptional,
Cleaner,
uncleaner
} from 'cleaners'
import {
asCouchDoc,
asMaybeConflictError,
asMaybeNotFoundError,
DatabaseSetup,
makeJsDesign
} from 'edge-server-tools'
import { ServerScope } from 'nano'

import { UserRow } from '../types/dbTypes'
import {
Device,
User,
UserCurrencyCodes,
UserCurrencyHours,
UserDevices,
UserNotifications
} from '../types/pushTypes'

export const asUserDevices: Cleaner<UserDevices> = asObject(asBoolean)
export type IDevicesByCurrencyHoursViewResponse = ReturnType<
typeof asUserDevices
>
export const asUserCurrencyHours: Cleaner<UserCurrencyHours> = asObject({
'1': asBoolean,
'24': asBoolean
})
export const asUserCurrencyCodes: Cleaner<UserCurrencyCodes> =
asMap(asUserCurrencyHours)

export const asUserNotifications: Cleaner<UserNotifications> = asObject({
enabled: asOptional(asBoolean),
currencyCodes: asUserCurrencyCodes
})

export const asCouchUser = asCouchDoc<Omit<User, 'userId'>>(
asObject({
devices: asUserDevices,
notifications: asUserNotifications
})
)

const wasCouchUser = uncleaner(asCouchUser)
type CouchUser = ReturnType<typeof asCouchUser>

export const usersSetup: DatabaseSetup = {
name: 'db_user_settings',
documents: {
'_design/filter': makeJsDesign('by-currency', ({ emit }) => ({
map: function (doc) {
const notifs = doc.notifications

// eslint-disable-next-line @typescript-eslint/strict-boolean-expressions
if (notifs?.enabled && notifs.currencyCodes) {
const codes = notifs.currencyCodes
for (const currencyCode in codes) {
for (const hours in codes[currencyCode]) {
const enabled = codes[currencyCode][hours]
// eslint-disable-next-line @typescript-eslint/strict-boolean-expressions
if (enabled) {
emit([currencyCode, hours], doc.devices)
}
}
}
}
}
})),
'_design/map': makeJsDesign('currency-codes', ({ emit }) => ({
map: function (doc) {
// eslint-disable-next-line @typescript-eslint/strict-boolean-expressions
if (doc.notifications?.currencyCodes) {
for (const code in doc.notifications.currencyCodes) {
emit(null, code)
}
}
},
reduce: function (keys, values, rereduce) {
return Array.from(new Set(values))
}
}))
}
}

// ------------------------------------------------------------------------------
// Functions associated with User
// ------------------------------------------------------------------------------

export const cleanUpMissingDevices = async (
connection: ServerScope,
user: User,
devices: Device[]
): Promise<void> => {
let updated = false
for (const device of devices) {
if (user.devices[device.deviceId] == null) {
user.devices[device.deviceId] = true
updated = true
}
}
if (updated) {
const db = connection.db.use(usersSetup.name)
const raw = await db.get(user.userId).catch(error => {
if (asMaybeNotFoundError(error) != null) return
throw error
})
if (raw == null) return
const { save } = makeUserRow(connection, raw)
await save()
}
}

export const makeUserRow = (connection: ServerScope, raw: unknown): UserRow => {
const db = connection.db.use(usersSetup.name)
let base = asCouchUser(raw)
const user: User = { ...base.doc, userId: base.id }
return {
user,
async save() {
let remote = base
while (true) {
// Write to the database:
const doc: CouchUser = {
doc: { ...user },
id: remote.id,
rev: remote.rev
}
const response = await db.insert(wasCouchUser(doc)).catch(error => {
if (asMaybeConflictError(error) == null) throw error
})

// If that worked, the merged document is now the latest:
if (response?.ok === true) {
base = doc
return
}

// Something went wrong, so grab the latest remote document:
const raw = await db.get(user.userId)
remote = asCouchUser(raw)
}
}
}
}

// eslint-disable-next-line @typescript-eslint/explicit-function-return-type
export const devicesByCurrencyHours = async (
connection: ServerScope,
hours: string,
currencyCode: string
) => {
return await connection.db
.use(usersSetup.name)
.view<IDevicesByCurrencyHoursViewResponse>('filter', 'by-currency', {
key: [currencyCode, hours]
})
}

export const saveUserToDB = async (
connection: ServerScope,
user: User
): Promise<void> => {
const db = connection.db.use(usersSetup.name)
const raw = await db.get(user.userId).catch(error => {
if (asMaybeNotFoundError(error) != null) return
throw error
})
if (raw == null) return
const { save } = makeUserRow(connection, raw)
await save()
}

export const fetchUser = async (
connection: ServerScope,
userId: string
): Promise<User | null> => {
const db = connection.db.use(usersSetup.name)
const raw = await db.get(userId).catch(error => {
if (asMaybeNotFoundError(error) != null) return
throw error
})
if (raw == null) return null
const userDoc = asCouchUser(raw)
return unpackUser(userDoc)
}

export const unpackUser = (doc: CouchUser): User => {
return { ...doc.doc, userId: doc.id }
}
export const packUser = (user: User): CouchUser => {
return {
doc: { devices: user.devices, notifications: user.notifications },
id: user.userId
}
}
22 changes: 22 additions & 0 deletions src/db/utils/couchOps.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
import { CouchDoc } from 'edge-server-tools'
import { DocumentScope } from 'nano'

export const saveToDB = async <T>(
db: DocumentScope<unknown>,
doc: CouchDoc<T>
): Promise<void> => {
try {
await db.insert({
...doc.doc,
_id: doc.id,
_rev: doc.rev ?? undefined
})
} catch (err: any) {
switch (err.statusCode) {
case 404:
throw new Error('Database does not exist')
default:
throw err
}
}
}
2 changes: 1 addition & 1 deletion src/middleware/withApiKey.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ export const withApiKey =

// Parse the key out of the headers:
const header = headers['x-api-key']
if (header == null) {
if (header == null || header === '') {
return errorResponse('Missing API key', { status: 401 })
}

Expand Down
29 changes: 0 additions & 29 deletions src/models/Device.ts

This file was deleted.

Loading