UNPKG

dynamodb-toolbox

Version:

Lightweight and type-safe query builder for DynamoDB and TypeScript.

53 lines (52 loc) 2.32 kB
import { EntityAction } from '../../../entity/index.js'; import { DynamoDBToolboxError } from '../../../errors/dynamoDBToolboxError.js'; import { Parser } from '../../../schema/actions/parse/parser.js'; import { QueryCommand } from '../../../table/actions/query/queryCommand.js'; import { $meta, $options, $pattern, $schema } from './constants.js'; export class IAccessPattern extends EntityAction { constructor(entity, schema, pattern, options = {}, meta = {}) { super(entity); this[$schema] = schema; this[$pattern] = pattern; this[$options] = options; this[$meta] = meta; } // IQueryCommand is needed for contravariance query(input) { const schema = this[$schema]; const transformedInput = schema !== undefined ? new Parser(schema).parse(input) : undefined; const pattern = this[$pattern]; if (pattern === undefined) { throw new DynamoDBToolboxError('actions.incompleteAction', { message: 'AccessPattern incomplete: Missing "pattern" property' }); } const defaultOptions = this[$options]; const { options: contextOptions, ...query } = pattern(transformedInput); return new QueryCommand(this.entity.table, [this.entity], query, { ...defaultOptions, ...contextOptions }); } } IAccessPattern.actionName = 'access-pattern'; export class AccessPattern extends IAccessPattern { constructor(entity, schema, pattern, options = {}, meta = {}) { super(entity, schema, pattern, options, meta); } schema(nextSchema) { return new AccessPattern(this.entity, nextSchema, this[$pattern], this[$options], this[$meta]); } pattern(nextPattern) { return new AccessPattern(this.entity, this[$schema], /** * @debt v3 "put query in a 'query' key so it's not polluted by the options" */ nextPattern, this[$options], this[$meta]); } options(nextOptions) { return new AccessPattern(this.entity, this[$schema], this[$pattern], typeof nextOptions === 'function' ? nextOptions(this[$options]) : nextOptions, this[$meta]); } meta(nextMeta) { return new AccessPattern(this.entity, this[$schema], this[$pattern], this[$options], nextMeta); } }