import { ContractType, ManageableFields, AuthInput, AuthenticationDefinition, Implementation, HandleResult } from './globalTypes.js' export const authorizedByPermission = ( auth: AuthenticationDefinition, authInput: AuthInput ) => typeof auth === 'boolean' || auth.some(x => (authInput.permissions || []).some(y => x === y)) export const getUserIdFields = (fields: ManageableFields): string[] => Object.entries(fields).filter(x => x[1]).map(x => x[0]) export 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) ) export const keyId = (index: string, id: string): string => `${index}:records:${id}` export type Get = ( contract: ContractType<'GET', IMPL, IN, OUT>, auth: AuthInput, id: string | string[] | undefined, body?: IN ) => Promise> export type Post = ( contract: ContractType<'POST', IMPL, IN, OUT>, auth: AuthInput, id: string | undefined, body: IN ) => Promise> export type Delete = ( contract: ContractType<'DELETE', IMPL, IN, OUT>, auth: AuthInput, id: string | string[] ) => Promise> export type Patch = ( contract: ContractType<'PATCH', IMPL, IN, OUT>, auth: AuthInput, id: string, body: IN ) => Promise> export type Put = ( contract: ContractType<'PUT', IMPL, IN, OUT>, auth: AuthInput, id: string, body: IN ) => Promise> export type AbstractBackend = { get: Get post: Post delete: Delete patch: Patch put: Put } export const forbidden = (data: any, errors: string[] = ['forbidden']) => ({ errorType: 'forbidden', data, status: 403, errors }) export const notFound = (data: any, errors: string[] = ['not found']) => ({ errorType: 'notFound', data, status: 404, errors })