UNPKG

dynamodb-toolbox

Version:

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

56 lines (55 loc) 2.54 kB
import { DynamoDBToolboxError } from '../../../errors/dynamoDBToolboxError.js'; import { Parser } from '../../../schema/actions/parse/parser.js'; import { QueryCommand } from '../../../table/actions/query/queryCommand.js'; import { $entities, TableAction } from '../../../table/index.js'; import { $meta, $options, $pattern, $schema } from './constants.js'; export class IAccessPattern extends TableAction { constructor(table, entities = [], schema, pattern, options = {}, meta = {}) { super(table, entities); 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.table, this[$entities], query, { ...defaultOptions, ...contextOptions }); } } IAccessPattern.actionName = 'access-pattern'; export class AccessPattern extends IAccessPattern { constructor(table, entities = [], schema, pattern, options = {}, meta = {}) { super(table, entities, schema, pattern, options, meta); } entities(...nextEntities) { return new AccessPattern(this.table, nextEntities, this[$schema], this[$pattern], this[$options]); } schema(nextSchema) { return new AccessPattern(this.table, this[$entities], nextSchema, this[$pattern], this[$options]); } pattern(nextPattern) { return new AccessPattern(this.table, this[$entities], this[$schema], /** * @debt v3 "put query in a 'query' key so it's not polluted by the options" */ nextPattern, this[$options]); } options(nextOptions) { return new AccessPattern(this.table, this[$entities], this[$schema], this[$pattern], typeof nextOptions === 'function' ? nextOptions(this[$options]) : nextOptions); } meta(nextMeta) { return new AccessPattern(this.table, this[$entities], this[$schema], this[$pattern], this[$options], nextMeta); } }