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.
49 lines
1.5 KiB
49 lines
1.5 KiB
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())
|