All files backendKv.ts

93.96% Statements 249/265
94.44% Branches 85/90
87.5% Functions 14/16
93.96% Lines 249/265

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 2661x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x     1x 1x     1x 5x       5x 5x 5x 5x 5x                   1x 1x 152x 52x 1x 1x 1x 1x 146x 1x 1x 1x 1x 64x 64x 64x 64x 64x 64x 64x 64x 64x 1x 100x 100x 100x 100x 100x 100x 100x 100x 100x 100x 100x 16x 10x 10x 10x 100x 78x 78x 72x 78x 70x 70x 6x 26x 6x 6x 6x 6x 6x 6x 6x 120x 70x 70x 6x 6x 26x 6x 6x 6x 6x 6x 6x 6x 6x 1x 1x 1092x 1092x 1092x 1092x 1092x 1092x 1092x 1092x 1092x 1092x 1092x 1092x 4x 4x 1092x 1092x 1092x 702x 702x 702x 1092x 1092x 1092x 1090x 1090x 1090x 1090x 1090x 1090x 1x 1x 58x 58x 58x 58x 58x 12x 12x 12x 12x 36x 12x 12x 6x 6x 6x 6x 46x 46x 46x 46x 58x 2x 2x 44x 58x 20x 20x 20x 20x 1x 1x 10x 10x 10x 10x 10x 10x 10x 10x 10x 8x 8x 10x 7x 7x 10x 2x 2x 8x 8x 8x 10x 2x 2x 6x 6x 6x 6x 6x 1x 1x 8x 8x 8x 8x 8x 8x 8x 8x 8x 6x 6x 8x 2x 2x 6x 6x 6x 8x 2x 2x 4x 4x 4x 4x 4x 1x 1x 76x 76x 76x 76x 76x 76x  
import { v4 as uuid } from 'uuid'
import { ContractType, ManageableFields, AuthInput, AuthenticationDefinition, Implementations, KeyValueStoreTypes, HandleResult } from './globalTypes.js'
import { memoryKV } from './memoryKv.js'
import { workerKv } from './workerKv.js'
import { AbstractBackend, forbidden, notFound } from './backendAbstract.js'
 
export type ValueType = string | ArrayBuffer | ArrayBufferView | ReadableStream
export type KvDataTypes = 'text' | 'json' | 'arrayBuffer' |'stream'
 
export type GetResultType<T> =
  T extends undefined ? string :
  T extends 'text' ? string :
  T extends 'json' ? object :
  T extends 'arrayBuffer' ? ArrayBuffer :
  T extends 'stream' ? ReadableStream :
  never
 
export type ListEntry = { name: string, expiration?: number, metadata: object}
/* eslint-disable camelcase */
export type KvListReturn ={
  keys: ListEntry[],
  list_complete: boolean,
  cursor: string
}
 
export type KV = {
  list: (options?: {prefix?: string, limit?: number, cursor?: string}) => Promise<KvListReturn>
  get: (<T extends KvDataTypes> (key:string, type?:T) => Promise<GetResultType<T> | null>)
  getWithMetadata:(<T extends KvDataTypes>(key:string, type?:T) => Promise<{value:GetResultType<T> | null, metadata: object | null}>),
  put: (key:string, value:ValueType, additional?: {metadata?:any, expiration?:number, expirationTtl?:number}) => Promise<void>
  delete: (key:string) => Promise<void>
};
 
type WorkerCache = {[key:string]: KV}
const clientInstance: WorkerCache = {}
 
/**
 * Global variable to set custom key value store implementation
 * **/
export declare var customKv:{[key:string]: () => KV}
 
const typeToString = (input:KeyValueStoreTypes) => typeof input === 'string' ? input : input.custom
export const client = (key:KeyValueStoreTypes):KV => clientInstance[typeToString(key)] || init(typeToString(key))
 
export const destroyAllClients = () => {
  for (const key of Object.keys(clientInstance)) delete clientInstance[key]
}
 
export const destroyClient = (key:string) => {
  delete clientInstance[key]
}
export const init = (key:any):KV => {
  if (key === 'worker') {
    clientInstance.worker = workerKv()
    return clientInstance.worker as KV
  }
 
  if (key === 'memory') {
    clientInstance.memory = memoryKV()
    return clientInstance.memory as KV
  }
  if (typeof customKv !== 'undefined') {
    if (key in customKv) {
      clientInstance[key] = customKv[key]()
      return clientInstance[key]
    }
  }

  throw new Error(`Unknown key value backend: '${key}'`)
}
 
const authorizedByPermission = (auth:AuthenticationDefinition, authInput:AuthInput) =>
  typeof auth === 'boolean' ||
  auth.some(x => (authInput.permissions || []).some(y => x === y))
 
const getUserIdFields = (fields:ManageableFields):string[] => Object.entries(fields).filter(x => x[1]).map(x => x[0])
 
const filterToAccess = (input:any[], auth:AuthenticationDefinition, authInput:AuthInput, fields:ManageableFields):any[] =>
  authorizedByPermission(auth, authInput) ? input : input.filter((x:any) => getUserIdFields(fields).some(y => x[y] === authInput.sub))
const keyId = (index:string, id:string):string => `${index}:records:${id}`
type KVi = Implementations.keyValue
 
const getByIdChecked = async (
  id:string,
  auth:AuthInput,
  type:KeyValueStoreTypes,
  index:string,
  authDef: AuthenticationDefinition,
  manageFields:ManageableFields) => {
  const result = await client(type).get(keyId(index, id), 'json')
  return filterToAccess([result], authDef, auth, manageFields)
}
export const get = async <IN, OUT>(
  contract: ContractType<'GET', KVi, IN, OUT>,
  auth: AuthInput,
  idIn: undefined | string | string[],
  input?:IN
): Promise<HandleResult<OUT>> => {
  const id: string | string[] = idIn || (input as any)?.id
  let cursor = (input as any)?.cursor
  const limit = (input as any)?. limit || 64
  const type = contract.implementation.backend
  const index = contract.implementation.prefix
  if (Array.isArray(id)) {
    if (id.length === 0) return { result: [] as any }
    const docs = (await Promise.all(id.map(x => client(type).get(keyId(index, x), 'json'))))
      .filter(x => x != null)
    return { result: filterToAccess(docs, contract.authentication, auth, contract.manageFields) as any }
  } else if (id) {
    const result = await client(type).get(keyId(index, id), 'json')
    if (!result) return notFound({ id, input })
    const filtered = filterToAccess([result], contract.authentication, auth, contract.manageFields)
    if (filtered.length === 0) return forbidden(input)
    return { result: filtered as any }
  }
 
  if (!contract.implementation.allowGetAll) return { errorType: 'badInput', status: 400, errors: ['Get all is disabled, id must be provided'] }
 
  const accessAll = authorizedByPermission(contract.authentication, auth)
  const listId : Promise<object|null>[] = []
 
  const result:KvListReturn = await client(type)
    .list({ limit: Math.max(10, limit), cursor, prefix: `${index}:records` })
  result.keys.forEach(async (x:ListEntry) => {
    if (accessAll || (x.metadata as any).createdBy === auth.sub) {
      listId.push(client(type).get(x.name, 'json'))
    }
  })
 
  if (listId.length >= limit) cursor = null
  if (result.list_complete) cursor = null
 
  return {
    result: (await Promise.all(listId) as any).filter((x:any) => x != null),
    cursor: result.cursor,
    more: !result.list_complete
  }
}
 
export const post = async <IN, OUT>(
  contract: ContractType<'POST', KVi, IN, OUT>,
  auth:AuthInput,
  id: string| undefined,
  body: IN): Promise<HandleResult<OUT>> => {
  const type = contract.implementation.backend
  const index = contract.implementation.prefix
 
  const newId = id || uuid()
 
  const newBody: {[key:string]:any} = { ...body }
 
  if (contract.manageFields.id === true) {
    newBody.id = newId
  }
 
  const metadata:{[key:string]:any} = {}
  if (contract.manageFields.createdBy === true) {
    newBody.createdBy = auth.sub
    metadata.createdBy = auth.sub
  }
  // Maybe skip check if it is generated?
  const got = await client(type).get(keyId(index, newId))
  if (got) return { errorType: 'conflict', data: body, status: 409, errors: [] }
 
  // TODO returned without the full id, that contains the index, or maybe always remove the index when returning?
  await client(type).put(keyId(index, newId), JSON.stringify(newBody), { metadata })
 
  return { result: newBody as any }
}
 
export const del = async <IN, OUT>(
  contract: ContractType<'DELETE', KVi, IN, OUT>,
  auth:AuthInput,
  id: string|string[]
): Promise<HandleResult<OUT>> => {
  if (Array.isArray(id)) {
    const data = await Promise.all(
      id.map(async (x) => ({ id, result: await del(contract, auth, x) })))
    const errors = data.reduce(
      (p, c) => p.concat(Array.isArray(c.result.errors) && c.result.errors.length
        ? c.result.errors
        : []), [] as (string[]))
    if (errors.length) {
      return { errorType: 'forbidden', data, status: 403, errors }
    }
    return { result: {} as any }
  }
  const type = contract.implementation.backend
  const index = contract.implementation.prefix
  const result = await getByIdChecked(id, auth, type, index, contract.authentication, contract.manageFields)
 
  if (result.length === 1 && result[0] === null) {
    return notFound({ id })
  }
 
  if (!result || result.length === 0) return forbidden(id, [`forbidden - could not delete item: ${id} `])
 
  await client(type).delete(keyId(index, id))
  return { result: {} as any }
}
 
export const patch = async <IN, OUT>(
  contract: ContractType<'PATCH', KVi, IN, OUT>,
  auth:AuthInput,
  id: string,
  body: IN
): Promise<HandleResult<OUT>> => {
  const type = contract.implementation.backend
  const index = contract.implementation.prefix
  const result = await getByIdChecked(id, auth, type, index, contract.authentication, contract.manageFields)
  if (!result || result.length === 0) return forbidden({ id, body })
 
  const newBody:{[key:string]:any} = { ...result[0] }
  for (const [key, value] of Object.entries(body)) {
    newBody[key] = value
  }
  if (contract.manageFields.createdBy === true) {
    newBody.createdBy = result[0].createdBy
  }
 
  const key = keyId(index, id)
  const { value, metadata } = await client(type).getWithMetadata(key)
  if (value == null) {
    return notFound({ id, body })
  }
 
  await client(type).put(key, JSON.stringify(newBody), { metadata })
 
  return { result: {} as any }
}
 
export const put = async <IN, OUT>(
  contract: ContractType<'PUT', KVi, IN, OUT>,
  auth:AuthInput,
  id: string,
  body: IN
): Promise<HandleResult<OUT>> => {
  const type = contract.implementation.backend
  const index = contract.implementation.prefix
  const result = await getByIdChecked(id, auth, type, index, contract.authentication, contract.manageFields)
  if (!result || result.length === 0) return forbidden({ id, body })
 
  const newBody :{[key:string]:any} = { ...body }
  if (contract.manageFields.createdBy === true) {
    newBody.createdBy = result[0].createdBy
  }
 
  const key = keyId(index, id)
  const { value, metadata } = await client(type).getWithMetadata(key)
  if (value == null) {
    return notFound({ id, body })
  }
 
  await client(type).put(key, JSON.stringify(newBody), { metadata })
 
  return { result: {} as any }
}
 
export const getKvProvider = ():AbstractBackend<Implementations.keyValue> => ({
  get,
  post,
  put,
  patch,
  delete: del
})