[ABANDONED] API server for Flexor social network.
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 

65 lines
2.2 KiB

// database.ts
// Copyright (C) 2020 Dwayne Harris
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <https://www.gnu.org/licenses/>.
import { CosmosClient, Container, SqlQuerySpec } from '@azure/cosmos'
import { Logger } from 'fastify'
import trim from 'lodash/trim'
import { QueryParams } from '../types'
export const containerFor = (client: CosmosClient, containerId: string) => client.database('Flexor').container(containerId)
export function createQuerySpec(query: string, params: QueryParams = {}): SqlQuerySpec {
return {
query,
parameters: Object.entries(params).map(([key, value]) => {
return {
name: key.startsWith('@') ? key : `@${key}`,
value,
}
})
}
}
interface QueryItemsOptions {
container: Container,
query: string | SqlQuerySpec,
logger?: Logger
}
export async function queryItems<T>(options: QueryItemsOptions): Promise<T[]> {
const { container, query, logger } = options
const { resources, requestCharge } = await container.items.query<T>(query, {}).fetchAll()
if (logger) logger.trace('Query: %d', requestCharge)
return resources
}
interface GetItemOptions {
container: Container
id: string
partitionKey?: string
logger?: Logger
}
export async function getItem<T>(options: GetItemOptions): Promise<T | undefined> {
const { container, id, partitionKey, logger } = options
const { resource, requestCharge } = await container.item(id, partitionKey ?? id).read<T>()
if (logger) logger.trace('Get: %d', requestCharge)
return resource
}
export const normalize = (text: string) => trim(text.replace(/[^A-Za-z0-9]/g, '-').toLowerCase())