import { DocumentClient } from 'aws-sdk/clients/dynamodb'; import { ExpressionAttributeNameMap } from 'aws-sdk/clients/dynamodb'; /** * Set of helper methods to build ConditionExpressions used in DynamoDB delete, put and update operations, and * FilterExpression used in DynamoDB query and scan operations. All of the condition based methods return a * {@link Condition.Resolver} function in the form of '(exp: ConditionExpression): string' this allow conditions * to be composed together and even extended in a very simple way. * * * See [Comparison Operator and Function Reference](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/Expressions.OperatorsAndFunctions.html) * for details on how each of the below comparison operations and functions work. * * * Condition is also used by {@link fields} to allow each field type to only expose the conditions that the field supports. * * * @example [examples/Condition.ts]{@link https://github.com/JasonCraftsCode/dynamodb-datamodel/tree/main/examples/Condition.ts}, (imports: [examples/Table.ts]{@link https://github.com/JasonCraftsCode/dynamodb-datamodel/tree/main/examples/Table.ts}) * ```typescript * [[include:Condition.ts]] * ``` * * * Note: Condition is a class that contains only static methods to support using javascript reserved words as * method names, like '{@link in}'. Condition is also a namespace to scope the Condition specific typings, like Resolver. * @public */ export declare class Condition { /** * Inserts a path for a value in below conditions methods to allow conditions to compare two fields against each other. * @example * ```typescript * // Expands to: '#n0 = #n1' * const condition = Condition.eq('name', Condition.path('nickname')); * ``` * @param value - Path to use for a condition value. * @returns Resolver to use when generate condition expression. */ static path(value: string): Condition.ValueResolver; /** * Inserts the size of the attribute value to compare the data size to a static value or another attribute value. * * * Supported Types: * * - String: length of string. * - Binary: number of bytes in value. * - *Set: number of elements in set. * - Map: number of child elements. * - List: number of child elements. * * @example * ```typescript * // Expands to: 'size(#n0) = :v0' * const condition = Condition.eq(Condition.size('name'), 4); * ``` * @param path - Attribute path to get size of value for. * @returns Resolver to use when generate condition expression. */ static size(path: string): Condition.ValueResolver; /** * General compare condition used by eq, ne, lt, le, gt, and ge. * @example * ```typescript * // Expands to: '#n0 <> :v0' * const condition = Condition.compare('name', '<>', 'value'); * ``` * @param left - Path to resolve or add. * @param op - Compare operation to use. * @param right - Value to resolve or add. * @returns Resolver to use when generate condition expression. */ static compare(left: Condition.Path, op: Condition.CompareOperators, right: Condition.Value): Condition.Resolver; /** * '=' - Equal condition compares if an attribute value is equal to a value or another attribute. * @example * ```typescript * // Expands to: '#n0 = :v0' * const condition = Condition.eq('name', 'value'); * ``` * @param left - Path to attribute or size of attribute to compare. * @param right - Value (or path to attribute) to check if equal to. * @returns Resolver to use when generate condition expression. */ static eq(left: Condition.Path, right: Condition.Value): Condition.Resolver; /** * '\<\>' - Not equal condition compares if an attribute value is not equal to a value or another attribute. * @example * ```typescript * // Expands to: '#n0 <> :v0' * const condition = Condition.ne('name', 'value'); * ``` * @param left - Path to attribute or size of attribute to compare. * @param right - Value (or path to attribute) to check if not equal to. * @returns Resolver to use when generate condition expression. */ static ne(left: Condition.Path, right: Condition.Value): Condition.Resolver; /** * '\<' - Less then condition compares if an attribute value is less then a value or another attribute. * @example * ```typescript * // Expands to: '#n0 < :v0' * const condition = Condition.lt('name', 'value'); * ``` * @param left - Path to attribute or size of attribute to compare. * @param right - Value (or path to attribute) to check if less then. * @returns Resolver to use when generate condition expression. */ static lt(left: Condition.Path, right: Condition.Value): Condition.Resolver; /** * '\<=' - Less then or equal to condition compares if an attribute value is less then or equal to a value or another attribute. * @example * ```typescript * // Expands to: '#n0 <= :v0' * const condition = Condition.le('name', 'value'); * ``` * @param left - Path to attribute or size of attribute to compare. * @param right - Value (or path to attribute) to check if less then or equal to. * @returns Resolver to use when generate condition expression. */ static le(left: Condition.Path, right: Condition.Value): Condition.Resolver; /** * '\>' - Greater then condition compares if an attribute value is greater then a value or another attribute. * @example * ```typescript * // Expands to: '#n0 > :v0' * const condition = Condition.gt('name', 'value'); * ``` * @param left - Path to attribute or size of attribute to compare. * @param right - Value (or path to attribute) to check if greater then. * @returns Resolver to use when generate condition expression. */ static gt(left: Condition.Path, right: Condition.Value): Condition.Resolver; /** * '\>=' - Greater then or equal to condition compare sif an attribute value is greater then or equal to a value or another attribute. * @example * ```typescript * // Expands to: '#n0 >= :v0' * const condition = Condition.ge('name', 'value'); * ``` * @param left - Path to attribute or size of attribute to compare. * @param right - Value (or path to attribute) to check if greater then or equal to. * @returns Resolver to use when generate condition expression. */ static ge(left: Condition.Path, right: Condition.Value): Condition.Resolver; /** * 'BETWEEN' - Between condition compares if an attribute value is between two values or other attributes. * Condition.between('path', 1, 2) will have the same outcome as * Condition.and(Condition.ge('path', 1), Condition.le('path', 2)) * @example * ```typescript * // Expands to: '#n0 BETWEEN :v0 AND :v1' * const condition = Condition.between('name', 1, 2); * ``` * @param path - Path to attribute or size of attribute to compare. * @param from - Value (or path to attribute) to check if greater then and equal to. * @param to - Value (or path to attribute) to check if less then and equal to. * @returns Resolver to use when generate condition expression. */ static between(path: string, from: Condition.Value, to: Condition.Value): Condition.Resolver; /** * 'IN' - In condition compares the value of an attribute is equal to any of the list values or other attributes. * @example * ```typescript * // Expands to: '#n0 IN (:v0, :v1, :v2)' * const condition = Condition.in('name', [1, 2, 3]); * ``` * @param path - Path to attribute to get the value from. * @param values - List of the values to check if equal to path attribute value. * @returns Resolver to use when generate condition expression. */ static in(path: string, values: Condition.Value[]): Condition.Resolver; /** * 'contains' Contains function checks if the attribute string or set contains the string value. * @example * ```typescript * // Expands to: 'contains(#n0, :v0)' * const condition = Condition.contains('name', 'value'); * ``` * Supported Types: String, *Set * @param path - Path to attribute to get the value from. * @param value - String to check if the attribute value contains. * @returns Resolver to use when generate condition expression. */ static contains(path: string, value: string): Condition.Resolver; /** * 'begins_with' - Begins with function checks to see if a string attribute begins with a string value. * Supported Types: String * @example * ```typescript * // Expands to: 'begins_with(#n0, :v0)' * const condition = Condition.beginsWith('name', 'value'); * ``` * @param path - Path to attribute to get the value from. * @param value - String to check if the path attribute value begins with. * @returns Resolver to use when generate condition expression. */ static beginsWith(path: string, value: string): Condition.Resolver; /** * 'attribute_type' - Attribute type function checks to see if the attribute is of a certain data type. * @example * ```typescript * // Expands to: 'attribute_type(#n0, :v0)' * const condition = Condition.type('name', 'S'); * ``` * @param path - Path to attribute to get the value from. * @param type - Type to check that the path attribute value matches. * @returns Resolver to use when generate condition expression. */ static type(path: string, type: Table.AttributeTypes): Condition.Resolver; /** * 'attribute_exists' - Attribute exists function check if the attribute exists for the item. * @example * ```typescript * // Expands to: 'attribute_exists(#n0)' * const condition = Condition.exists('name'); * ``` * @param path - Path to attribute to get the value from. * @returns Resolver to use when generate condition expression. */ static exists(path: string): Condition.Resolver; /** * 'attribute_not_exists' - Attribute not exists function checks if the attribute does not exists for the item. * @example * ```typescript * // Expands to: 'attribute_not_exists(#n0)' * const condition = Condition.notExists('name'); * ``` * @param path - Path to attribute to get the value from. * @returns Resolver to use when generate condition expression. */ static notExists(path: string): Condition.Resolver; /** * 'AND' - And logical evaluations check if all sub condition is true. * This condition will be evaluated with an outer '()' to ensure proper order of evaluation. * @example * ```typescript * // Expands to: '(#n0 = :v0 AND #n0 = :v1 AND #n0 = :v2)' * const condition = Condition.and(Condition.eq('name', 1), Condition.eq('name', 2), Condition.eq('name', 3)); * ``` * @param conditions - List of conditions to evaluate with AND. * @returns Resolver to use when generate condition expression. */ static and(...conditions: Condition.Resolver[]): Condition.Resolver; /** * 'OR' - Or logical evaluations check if at least one sub condition is true. * This condition will be evaluated with an outer '()' to ensure proper order of evaluation. * @example * ```typescript * // Expands to: '(#n0 = :v0 OR #n0 = :v1 OR #n0 = :v2)' * const condition = Condition.or(Condition.eq('name', 1), Condition.eq('name', 2), Condition.eq('name', 3)); * ``` * @param conditions - List of conditions to evaluate with OR * @returns Resolver to use when generate condition expression. */ static or(...conditions: Condition.Resolver[]): Condition.Resolver; /** * 'NOT' - Not logical evaluations inverts the condition so true is now false or false is now true. * This condition will be evaluated with an outer '()' to ensure proper order of evaluation. * @example * ```typescript * // Expands to: '(NOT #n0 = :v0)' * const condition = Condition.not(Condition.eq('name', 1)); * ``` * @param condition - Condition to invert the value of. * @returns Resolver to use when generate condition expression. */ static not(condition: Condition.Resolver): Condition.Resolver; } /** * Is also a namespace for scoping Condition based interfaces and types. * @public * */ export declare namespace Condition { /** * Supported compare based operators for conditions expressions. */ export type CompareOperators = '=' | '<>' | '<' | '<=' | '>' | '>='; /** * Supported logical based operators for condition expressions. */ export type LogicalOperators = 'AND' | 'OR' | 'NOT'; /** * Support operators and functions for condition expressions. */ export type Operators = CompareOperators | 'BETWEEN' | 'IN' | 'begins_with' | 'contains' | 'attribute_type' | 'attribute_exists' | 'attribute_not_exists' | 'size' | LogicalOperators; /** * Expression object used in the condition resolver to resolve the condition to an expression. */ export interface Expression { /** * See {@link ExpressionAttributes.addPath} for details. */ addPath(path: string): string; /** * See {@link ExpressionAttributes.addValue} for details. */ addValue(value: Table.AttributeValues): string; /** * Add a condition path either directly or by resolving the path. * @param path - Value to add or add via resolving. * @returns Generated name alias to use in condition expression. */ resolvePath(path: Condition.Path): string; /** * Add a condition value either directly or by resolving the values. * @param values - Array of values to add or add via resolving. * @returns Generated value alias to use in condition expression. */ resolveValues(values: Condition.Value[]): string[]; } /** * Resolver function is return by most of the above Conditions methods. Returning a function allows conditions * to easily be composable and extensible. This allows consumers to create higher level conditions that are composed * of the above primitive conditions or support any new primitives that AWS would add in the future. * @param exp - Object to get path and value aliases. * @param type - Argument to enforce type safety for conditions that only work on certain types. */ export type Resolver = (exp: Expression, type: 'BOOL') => string; /** * Value Resolver function is return by the path and size Condition methods. Returning a function allows conditions * to easily be composable and extensible. This allows consumers to create higher level conditions that are composed * of the above primitive conditions or support any new primitives that AWS would add in the future. * @param exp - Object to get path and value aliases. * @param type - Argument to enforce type safety for conditions that only work on certain types. */ export type ValueResolver = (exp: Expression, type: 'S') => string; /** * The value used in the condition methods. Can either be a primitive DynamoDB value or a Resolver function, * which allows for the use of functions like '{@link size}' or reference other attributes. */ export type Value = T | ValueResolver; /** * The path or name used in the conditions methods. Can either be a string or a Resolver function, which allows * for the use of functions like '{@link size}'. */ export type Path = string | ValueResolver; } /** * Object passed down to Condition.Resolver functions to support getting path and value aliases and * provide context to the resolver function to support advanced condition resolvers. * @public */ export declare class ConditionExpression implements Condition.Expression { /** * Object for getting path and value aliases. */ attributes: Table.ExpressionAttributes; /** * Initialize ConditionExpression with existing or new {@link ExpressionAttributes}. * @param attributes - Object used to get path and value aliases. */ constructor(attributes: Table.ExpressionAttributes); /** * See {@link ExpressionAttributes.addPath} for details. */ addPath(path: string): string; /** * See {@link ExpressionAttributes.addValue} for details. */ addValue(value: Table.AttributeValues): string; /** @inheritDoc {@inheritDoc (Condition:namespace).Expression.resolvePath} */ resolvePath(path: Condition.Path): string; /** @inheritDoc {@inheritDoc (Condition:namespace).Expression.resolveValues} */ resolveValues(values: Condition.Value[]): string[]; /** * Expands a list of conditions into an 'AND' expression. * This method is different then evaluating the above '{@link and}' method, since it will not surround the condition with '()'. * @param conditions - List of conditions to evaluate with AND. * @param exp - Used when evaluation conditions and store the names and values mappings. * @returns The list of conditions expanded as a string with 'AND' between each. */ static buildExpression(conditions: Condition.Resolver[], exp: Condition.Expression): string; /** * Helper function to set a 'FilterExpression' or 'ConditionExpression' property on the params argument if there are conditions to resolve. * @param conditions - List of conditions to evaluate with AND. * @param exp - Used when evaluation conditions and store the names and values mappings. * @param type - The type of expression to set either 'filter' or 'condition', * @param params - Params used for DocumentClient query and scan methods. * @returns The params argument passed in. */ static addParams(params: { ConditionExpression?: string; FilterExpression?: string; }, attributes: Table.ExpressionAttributes, type: 'filter' | 'condition', conditions?: Condition.Resolver[]): void; /** * Determines if a value is a resolver function or a basic type. * @param value - Path, value or resolver to inspect. * @returns True if value is a resolver and false if value is a basic type. */ static isResolver(value: Condition.Path | Condition.Value): value is Condition.ValueResolver; } /** * Object used in Condition, KeyCondition and Update resolver methods to create attribute names and values * aliases and store the mappings for use in ExpressionAttributeNames and ExpressionAttributeValues params. * @public */ export declare class ExpressionAttributes implements Table.ExpressionAttributes { /** * RegEx that validates an attribute name would not need to use an alias. */ static validAttributeNameRegEx: RegExp; /** * Validates that an attribute name can be used without an alias. * @param name - Name of an attribute. * @returns true if the attribute name is valid. */ static isValidAttributeName(name: string): boolean; /** * Property function to determine if the name is a reserved word and should use an alias. * For a current list of reserved words see DynamoDB-ReservedWords module in NPM. * The reason to set isReservedName and isValidName is to allow the attribute names to be directly * embedded into the expression string, which can make them easier to read. * @defaultValue '() =\> false;' - To use aliases for all attribute names. */ isReservedName: (name: string) => boolean; /** * Property function to determine if the name is valid to use without an alias. * Can use ExpressionAttribute.isValidAttributeName. * WARNING: Must be used with a proper isReservedName function to ensure reserved words are not used * without an alias otherwise the operations will return an error. * @defaultValue '() =\> false;' - To use aliases for all attribute names. */ isValidName: (name: string) => boolean; /** * Parse all names into paths by using the pathDelimiter, to make working with nested attributes easy. * @defaultValue true - Since most all names won't contain pathDelimiter then just do this by default. */ treatNameAsPath: boolean; /** * Delimiter to use for paths. * @defaultValue '.' - Period is used in javascript for nested objects. */ pathDelimiter: string; /** * Attribute names mapping, used to populate the ExpressionAttributeNames param. */ names: ExpressionAttributeNameMap; /** * Auto incrementing name id used in names mapping. * @defaultValue 0 */ nextName: number; /** * Attribute values mapping, used to populate the ExpressionAttributeValues param. */ values: Table.AttributeValuesMap; /** * Auto incrementing value id used in values mapping. * @defaultValue 0 */ nextValue: number; /** * Parse an attribute path and adds the names to the names mapping as needed and hands back an alias to use * in an expression. If the name already exists in the map the existing alias will be used. * When this.treatNameAsPath is true the name argument will be parsed as a path and will handle arrays * embedded in the path correctly, to allow access to all deep attribute. * @param name - Attribute path that can be delimited by a pathDelimiter and contain array notations '[]'. * @returns Alias path to use for the attribute name or the name if not aliasing is needed, delimited by '.'. */ addPath(name: string): string; /** * Adds the value to the values map and hands back an alias to use in ab expression. * A new alias will always be created every time addValue is called. * @param value - Value to add to the values map. * @returns Alias to use in place of the value. */ addValue(value: Table.AttributeValues): string; /** * Gets the names map to assign to ExpressionAttributeNames. * @returns The map of all names added. */ getPaths(): ExpressionAttributeNameMap | void; /** * Gets the values map to assign to ExpressionAttributeValues. * @returns The map of all values added. */ getValues(): Table.AttributeValuesMap | void; /** * Helper method to set ExpressionAttributeNames and ExpressionAttributeValues values on the input argument. * @param params - Input params used for DocumentClient put, delete, update, query and scan methods. * @returns The input params argument passed in. */ static addParams(params: Table.ExpressionAttributeParams, attributes: Table.ExpressionAttributes): void; /** * Private method to add an attribute name to the names mapping if needed and hand back an alias to use in * an expression. * @param name - Attribute name. * @returns Alias to use for the attribute name or the name if not aliasing is needed. */ private addName; } /** * Collection of functions for constructing a Model schema with Field objects and the Field classes. * @example [examples/Fields.ts]{@link https://github.com/jasoncraftscode/dynamodb-datamodel/tree/main/examples/Fields.ts}, (imports: [examples/Table.ts]{@link https://github.com/jasoncraftscode/dynamodb-datamodel/tree/main/examples/Table.ts}) * ```typescript * [[include:Fields.ts]] * ``` * @public */ export declare class Fields { /** * Creates a string field object to use in a {@link Model.schema}. * @param options - Options to initialize field with. * @returns New FieldString object. */ static string(options?: Fields.BaseOptions): Fields.FieldString; /** * Creates a number field object to use in a {@link Model.schema}. * @param options - Options to initialize field with. * @returns New FieldNumber object. */ static number(options?: Fields.BaseOptions): Fields.FieldNumber; /** * Creates a binary field object to use in a {@link Model.schema}. * @param options - Options to initialize field with. * @returns New FieldBinary object. */ static binary(options?: Fields.BaseOptions): Fields.FieldBinary; /** * Creates a boolean field object to use in a {@link Model.schema}. * @param options - Options to initialize field with. * @returns New FieldBoolean object. */ static boolean(options?: Fields.BaseOptions): Fields.FieldBoolean; /** * Creates a string set field object to use in a {@link Model.schema}. * @param options - Options to initialize field with. * @returns New FieldStringSet object. */ static stringSet(options?: Fields.SetOptions): Fields.FieldStringSet; /** * Creates a number set field object to use in a {@link Model.schema}. * @param options - Options to initialize field with. * @returns New FieldNumberSet object. */ static numberSet(options?: Fields.SetOptions): Fields.FieldNumberSet; /** * Creates a binary set field object to use in a {@link Model.schema}. * @param options - Options to initialize field with. * @returns New FieldBinarySet object. */ static binarySet(options?: Fields.SetOptions): Fields.FieldBinarySet; /** * Creates a list field object to use in a {@link Model.schema}. * @param options - Options to initialize field with. * @returns New FieldList object. */ static list(options?: Fields.BaseOptions): Fields.FieldList; /** * Creates a schema based list field object to use in a {@link Model.schema}. * @param V - Interface of model to use for schema. * @param options - Options to initialize field with. * @returns New FieldModelList object. */ static modelList(options: Fields.ModelListOptions): Fields.FieldModelList; /** * Creates a map field object to use in a {@link Model.schema}. * @param options - Options to initialize field with. * @returns New FieldMap object. */ static map(options?: Fields.BaseOptions): Fields.FieldMap; /** * Creates a schema based map field object to use in a {@link Model.schema}. * @param V - Interface of model to use for schema. * @param options - Options to initialize field with. * @returns New FieldModelMap object. */ static modelMap(options: Fields.ModelMapOptions): Fields.FieldModelMap; /** * Creates a schema based map field object to use in a {@link Model.schema}. * @param V - Interface of model to use for schema. * @param options - Options to initialize field with. * @returns New FieldModel object. */ static model(options: Fields.ModelOptions): Fields.FieldModel; /** * Creates a date field object to use in a {@link Model.schema}, stored as a number in the table. * @param options - Options to initialize field with. * @returns New FieldDate object. */ static date(options?: Fields.BaseOptions): Fields.FieldDate; /** * Creates a hidden field object to use in a {@link Model.schema}, which doesn't get set in the table. * @returns New FieldHidden object. */ static hidden(): Fields.FieldHidden; /** * Creates a split field object to use in a {@link Model.schema}. which can be used to split a model property into two or more * table attributes. This is commonly used as an model id property which gets slit into the table's partition and sort keys. * Example: Model schema contains 'id: Fields.split(\{ aliases: ['P','S'] \})' and when id = 'guid.date' the field will split the id value * in to the table primary key of \{ P: 'guid', S: 'date' \} * * @example [examples/Fields.split.ts]{@link https://github.com/jasoncraftscode/dynamodb-datamodel/tree/main/examples/Fields.split.ts}, (imports: [examples/Table.ts]{@link https://github.com/jasoncraftscode/dynamodb-datamodel/tree/main/examples/Table.ts}) * ```typescript * [[include:Fields.split.ts]] * ``` * * @param options - Options to initialize field with. * @returns New FieldSplit object. */ static split(options: Fields.SplitOptions): Fields.FieldSplit; /** * Creates an indices based slots composite field object which can then return FieldCompositeSlot by index to use in a {@link Model.schema}. * * @example [examples/Fields.composite.ts]{@link https://github.com/jasoncraftscode/dynamodb-datamodel/tree/main/examples/Fields.composite.ts}, (imports: [examples/Table.ts]{@link https://github.com/jasoncraftscode/dynamodb-datamodel/tree/main/examples/Table.ts}) * ```typescript * [[include:Fields.composite.ts]] * ``` * * @param options - Options to initialize field with. * @returns New composite object with array field slots. */ static composite(options: Fields.CompositeOptions): Fields.FieldComposite; /** * Creates an name based slots composite field object which can then return FieldCompositeSlot by name to use in a {@link Model.schema}. * * @example [examples/Fields.compositeNamed.ts]{@link https://github.com/jasoncraftscode/dynamodb-datamodel/tree/main/examples/Fields.compositeNamed.ts}, (imports: [examples/Table.ts]{@link https://github.com/jasoncraftscode/dynamodb-datamodel/tree/main/examples/Table.ts}) * ```typescript * [[include:Fields.compositeNamed.ts]] * ``` * * @param T - Map of slot names to index * @param options - Options to initialize field with. * @returns New composite object with named field slots. */ static compositeNamed(options: Fields.CompositeNamedOptions): Fields.FieldCompositeNamed; /** * Creates a field that adds the Model name to a table attribute. * * @example [examples/Fields.type.ts]{@link https://github.com/jasoncraftscode/dynamodb-datamodel/tree/main/examples/Fields.type.ts}, (imports: [examples/Table.ts]{@link https://github.com/jasoncraftscode/dynamodb-datamodel/tree/main/examples/Table.ts}) * ```typescript * [[include:Fields.type.ts]] * ``` * * @param options - Options to initialize field with. * @returns New FieldType object. */ static type(options?: Fields.TypeOptions): Fields.FieldType; /** * Creates a field that add a created date to a table attribute. * @param options - Options to initialize field with. * @returns New FieldCreatedDate object. */ static createdDate(options?: Fields.CreatedDateOptions): Fields.FieldCreatedDate; /** * Creates a field that adds an updated date to a table attribute. * @param options - Options to initialize field with. * @returns New FieldUpdatedDate object. */ static updatedDate(options?: Fields.UpdateDateOptions): Fields.FieldUpdatedDate; /** * Creates a field that add a created date as a number in seconds since UTC UNIX epoch time (January 1, 1970 00:00:00 UTC) to a table attribute. * @param options - Options to initialize field with. * @returns New FieldCreatedNumberDate object. */ static createdNumberDate(options?: Fields.CreatedDateOptions): Fields.FieldCreatedNumberDate; /** * Creates a field that adds an updated date as a number in seconds since UTC UNIX epoch time (January 1, 1970 00:00:00 UTC) to a table attribute. * @param options - Options to initialize field with. * @returns New FieldUpdatedNumberDate object. */ static updatedNumberDate(options?: Fields.UpdateNumberDateOptions): Fields.FieldUpdatedNumberDate; /** * Creates a field that will be incremented with each update. It also supports preventing an update if * the table attribute doesn't match the model property. * @param options - Options to initialize field with. * @returns New FieldRevision object. */ static revision(options?: Fields.RevisionOptions): Fields.FieldRevision; } /** * Is also a namespace for scoping Condition based interfaces and types. * @public * */ export declare namespace Fields { /** * Used in TableContext to determine the scope the action is executed in. * @param single - Action will be preformed via the single item API. * @param batch - Action will be preformed via the batch read/write API. * @param transact - TAction will be preformed via the transaction read/write API. */ export type ActionScope = 'single' | 'batch' | 'transact'; /** * Context object passed to {@link Field.toTable} and {@link Field.toTableUpdate} to allow the fields to know */ export interface TableContext { /** * Type of action that will be run after all field's {@link Field.toTable} or {@link Field.toTableUpdate} are called. */ action: Table.ItemActions; /** * The scope the action is executed in. */ scope: ActionScope; /** * Array of conditions to resolve and joined with AND conditions, then set as the ConditionExpression * param before calling DynamoDB method. */ conditions: Condition.Resolver[]; /** * Options for the current {@link Model} method being called. */ options: Table.BaseOptions; /** * The model that is calling the field's {@link Field.toTable} or {@link Field.toTableUpdate} methods. */ model: Model.ModelBase; } /** * Context object passed to {@link Field.toModel} to allow the fields to know about the broader context * and provide more complex behavior. */ export interface ModelContext { /** * Type of action that ran before all field's {@link Field.toModel} are called. */ action: Table.ItemActions; /** * Options for the current {@link Model} method being called. */ options: Table.BaseOptions; /** * The model that is calling the field's {@link Field.toModel} method. */ model: Model.ModelBase; } /** * Defines the table attributes used by a field. */ export interface AttributeDefinition { /** * The type of the table attribute the field writes. */ type: Table.AttributeTypes; } /** * Defines the set of table attributes that are used by a field. */ export type AttributesSchema = { [key: string]: AttributeDefinition; }; /** * The core interface all Fields implement and is used by {@link Model} to basically map model data * to and from the table data. * @example Custom Field * ```typescript * class CustomField extends Field { * } * ``` */ export interface Field { /** * Initialize the field with the field name from the Model's schema and the model. * @param name - Name of the model attribute this field is set on. * @param model - Model this field is associated with. */ init(name: string, model: Model): void; /** * Method called **after** calling into the table object to read and write to the table. This method will convert the * table data into model data. * @param name - Name of the model attribute this field is associated with (generally same as {@link init} name argument). * @param tableData - Data from the table that needs to be mapped to the model data. * @param modelData - Data object for the model that this method will append to. * @param context - Current context this method is being called in. */ toModel(name: string, tableData: Table.AttributeValuesMap, modelData: Model.ModelData, context: ModelContext): void; /** * Method called **before** calling into the table object to read and write to the table. This method will convert the model data * into table data and append read or write conditions. * @param name - Name of the model attribute this field is associated with (generally same as {@link init} name argument). * @param modelData - Data from the model that needs to be mapped to the table data. * @param tableData - Data object for the table that this method will append to. * @param context - Current context this method is being called in. */ toTable(name: string, modelData: Model.ModelData, tableData: Table.AttributeValuesMap, context: TableContext): void; /** * Method called **before** calling into the table object to update the table. This method will convert the model data * into table data and append read or write conditions. * * * Note: Several Fields will just call toTable from toTableUpdate if they don't support any special update syntax. * @param name - Name of the model attribute this field is associated with (generally same as {@link init} name argument) * @param modelData - Data from the model that needs to be mapped to the table data. * @param tableData - Data object for the table that this method will append to. * @param context - Current context this method is being called in. */ toTableUpdate(name: string, modelData: Model.ModelUpdate, tableData: Update.ResolverMap, context: TableContext): void; } /** * Options used for creating {@link FieldBase}. * @param V - Type used for default value. */ export interface BaseOptions { /** * Table attribute to map this Model property to. */ alias?: string; /** * Value or function to get value from to use when the Model property is empty. */ default?: V | FieldBase.DefaultFunction; } /** * Base Field implementation used by many of the basic field types. * @param V - Type for the value of the field. * @public */ export class FieldBase implements Field { /** * Model name of the field, set by init function in Model or Field constructor. */ name?: string; /** * Table attribute to map this Model property to. */ alias?: string; /** * Value or function to get value from to use when the Model property is empty. */ default?: V | FieldBase.DefaultFunction; /** * Initialize the Field. * @param options - Options to initialize FieldBase with. */ constructor(options?: BaseOptions); /** @inheritDoc {@inheritDoc (Fields:namespace).Field.init} */ init(name: string, model: Model): void; /** @inheritDoc {@inheritDoc (Fields:namespace).Field.toModel} */ toModel(name: string, tableData: Table.AttributeValuesMap, modelData: Model.ModelData, context: ModelContext): void; /** @inheritDoc {@inheritDoc (Fields:namespace).Field.toTable} */ toTable(name: string, modelData: Model.ModelData, tableData: Table.AttributeValuesMap, context: TableContext): void; /** @inheritDoc {@inheritDoc (Fields:namespace).Field.toTableUpdate} */ toTableUpdate(name: string, modelData: Model.ModelUpdate, tableData: Update.ResolverMap, context: TableContext): void; /** * Name of table attribute. Used in Condition based Field methods. */ tableName(): string; /** * Get the default value to use in toTable if no value it set. * @param name - Model property name associated with field (passed into toTable). * @param modelData - Data from the model that to reference for default. * @param context - Current context this method is being called in. * @returns Default value to use. */ getDefault(name: string, modelData: Model.ModelData, context: TableContext): V | undefined; } /** * Is also a namespace for scoping FieldBase based interfaces and types. * @public */ export namespace FieldBase { /** * Function to get the default value when the model property is missing. * @param T - Value to return from default function. * @param name - Name of the model attribute this field is associated with (generally same as {@link init} name argument). * @param modelData - Data from the model that needs to be mapped to the table data. * @param context - Current context this method is being called in. * @returns default value for the model property if it is missing. */ export type DefaultFunction = (name: string, modelData: Model.ModelData, context: TableContext) => T; } /** * Base class for model property fields. * @param V - Type this field represents used in Condition methods. */ export class FieldExpression extends FieldBase { /** * Helper method that just calls {@link Condition.path} with tableName() as value param. * See {@link Condition.path} for more info and examples. */ path(): Condition.ValueResolver; /** * Helper method that just calls {@link Condition.eq} with tableName() as left param. * See {@link Condition.eq} for more info and examples. */ eq(v: Condition.Value): Condition.Resolver; /** * Helper method that just calls {@link Condition.ne} with tableName() as left param. * See {@link Condition.ne} for more info and examples. */ ne(v: Condition.Value): Condition.Resolver; /** * Helper method that just calls {@link Condition.lt} with tableName() as left param. * See {@link Condition.lt} for more info and examples. */ lt(v: Condition.Value): Condition.Resolver; /** * Helper method that just calls {@link Condition.le} with tableName() as left param. * See {@link Condition.le} for more info and examples. */ le(v: Condition.Value): Condition.Resolver; /** * Helper method that just calls {@link Condition.gt} with tableName() as left param. * See {@link Condition.gt} for more info and examples. */ gt(v: Condition.Value): Condition.Resolver; /** * Helper method that just calls {@link Condition.ge} with tableName() as left param. * See {@link Condition.ge} for more info and examples. */ ge(v: Condition.Value): Condition.Resolver; /** * Helper method that just calls {@link Condition.between} with tableName() as path param. * See {@link Condition.between} for more info and examples. */ between(from: Condition.Value, to: Condition.Value): Condition.Resolver; /** * Helper method that just calls {@link Condition.in} with tableName() as path param. * See {@link Condition.in} for more info and examples. */ in(v: Condition.Value[]): Condition.Resolver; /** * Helper method that just calls {@link Condition."type"} with tableName() as path param. * See {@link Condition."type"} for more info and examples. */ type(type: Table.AttributeTypes): Condition.Resolver; /** * Helper method that just calls {@link Condition.exists} with tableName() as path param. * See {@link Condition.exists} for more info and examples. */ exists(): Condition.Resolver; /** * Helper method that just calls {@link Condition.notExists} with tableName() as path param. * See {@link Condition.notExists} for more info and examples. */ notExists(): Condition.Resolver; } /** * See {@link Fields.string} for details. */ export class FieldString extends FieldExpression { /** * Helper method that just calls {@link Condition.size} with tableName() as path param. * See {@link Condition.size} for more info and examples. */ size(): Condition.ValueResolver; /** * Helper method that wraps {@link Condition.contains}. * See {@link Condition.contains} for more info and examples. */ contains(value: string): Condition.Resolver; /** * Helper method that wraps {@link Condition.beginsWith}. * See {@link Condition.beginsWith} for more info and examples. */ beginsWith(value: string): Condition.Resolver; } /** * See {@link Fields.number} for details. */ export class FieldNumber extends FieldExpression { } /** * See {@link Fields.binary} for details. */ export class FieldBinary extends FieldExpression { /** * Helper method that just calls {@link Condition.size} with tableName() as path param. * See {@link Condition.size} for more info and examples. */ size(): Condition.ValueResolver; } /** * See {@link Fields.boolean} for details. */ export class FieldBoolean extends FieldExpression { } /** * See {@link Fields.null} for details. */ export class FieldNull extends FieldExpression { } export interface SetOptions extends BaseOptions { /** * Defines the schema for the list type. */ useArrays?: boolean; } /** * Generic set property field is base class for {@link FieldStringSet}, {@link FieldStringSet}, and {@link FieldStringSet}. */ export class FieldSet extends FieldExpression { useArrays?: boolean; /** * Initialize the Field. * @param options - Options to initialize FieldBase with. */ constructor(options?: SetOptions); /** @inheritDoc {@inheritDoc (Fields:namespace).Field.toModel} */ toModel(name: string, tableData: Table.AttributeValuesMap, modelData: Model.ModelData, context: ModelContext): void; /** @inheritDoc {@inheritDoc (Fields:namespace).Field.toTable} */ toTable(name: string, modelData: Model.ModelData, tableData: Table.AttributeValuesMap, context: TableContext): void; /** @inheritDoc {@inheritDoc (Fields:namespace).Field.toTableUpdate} */ toTableUpdate(name: string, modelData: Model.ModelUpdate, tableData: Update.ResolverMap, context: TableContext): void; /** * Helper method that just calls {@link Condition.size} with tableName() as path param. * See {@link Condition.size} for more info and examples. */ size(): Condition.ValueResolver; /** * Helper method that just calls {@link Condition.contains} with tableName() as path param. * See {@link Condition.contains} for more info and examples. */ contains(value: string): Condition.Resolver; } /** * See {@link Fields.stringSet} for details. */ export class FieldStringSet extends FieldSet { } /** * See {@link Fields.numberSet} for details. */ export class FieldNumberSet extends FieldSet { } /** * See {@link Fields.binarySet} for details. */ export class FieldBinarySet extends FieldSet { } /** * See {@link Fields.list} for details. */ export class FieldList extends FieldExpression { /** * Helper method that just calls {@link Condition.size} with tableName() as path param. * See {@link Condition.size} for more info and examples. */ size(): Condition.ValueResolver; } /** * FieldModelList constructor options. */ export interface ModelListOptions extends BaseOptions { /** * Defines the schema for the list type. */ schema: Model.ModelSchemaT; } /** * See {@link Fields.modelList} for details. */ export class FieldModelList extends FieldList { /** * Defines the schema for the list type. */ schema: Model.ModelSchemaT; /** * Initializes FieldModelList with the options. * @param options - Options to initialize FieldModelList with. */ constructor(options: ModelListOptions); /** * Initializes the schema property. * See {@link Field.init} for more information. */ init(name: string, model: Model): void; /** @inheritDoc {@inheritDoc (Fields:namespace).Field.toModel} */ toModel(name: string, tableData: Table.AttributeValuesMap, modelData: Model.ModelData, context: ModelContext): void; /** @inheritDoc {@inheritDoc (Fields:namespace).Field.toTable} */ toTable(name: string, modelData: Model.ModelData, tableData: Table.AttributeValuesMap, context: TableContext): void; /** @inheritDoc {@inheritDoc (Fields:namespace).Field.toTableUpdate} */ toTableUpdate(name: string, modelData: Model.ModelUpdate, tableData: Update.ResolverMap, context: TableContext): void; } /** * See {@link Fields.map} for details. */ export class FieldMap extends FieldExpression<{ [key: string]: V; }> { /** * Helper method that just calls {@link Condition.size} with tableName() as path param. * See {@link Condition.size} for more info and examples. */ size(): Condition.ValueResolver; } /** * Condition.Expression used for nested conditions */ /** * FieldModelMap constructor options. * @param V - Type of the map value. */ export interface ModelMapOptions extends BaseOptions<{ [key: string]: V; }> { /** * Model schema to use as the value for the Map */ schema: Model.ModelSchemaT; } /** * See {@link Fields.modelMap} for details. */ export class FieldModelMap extends FieldMap { /** * Model schema to use as the value for the Map */ schema: Model.ModelSchemaT; /** * Constructs a FieldModelMap object with options. * @param options - Options to initialize model map with. */ constructor(options: ModelMapOptions); /** * Initializes the schema property. * See {@link Field.init} for more information. */ init(name: string, model: Model): void; /** @inheritDoc {@inheritDoc (Fields:namespace).Field.toModel} */ toModel(name: string, tableData: Table.AttributeValuesMap, modelData: Model.ModelData, context: ModelContext): void; /** @inheritDoc {@inheritDoc (Fields:namespace).Field.toTable} */ toTable(name: string, modelData: Model.ModelData, tableData: Table.AttributeValuesMap, context: TableContext): void; /** @inheritDoc {@inheritDoc (Fields:namespace).Field.toTableUpdate} */ toTableUpdate(name: string, modelData: Model.ModelUpdate, tableData: Update.ResolverMap, context: TableContext): void; } /** * FieldModel constructor options. */ export interface ModelOptions extends BaseOptions { /** * Model schema to use for the FieldModel */ schema: Model.ModelSchemaT; } /** * See {@link Fields.model} for details. */ export class FieldModel extends FieldExpression { /** * Model schema to use for writing to this field */ schema: Model.ModelSchemaT; /** * Initialize the class with options. * @param options - Options to initialize the class with. */ constructor(options: ModelOptions); /** * Initializes the schema property. * See {@link Field.init} for more information. */ init(name: string, model: Model): void; /** @inheritDoc {@inheritDoc (Fields:namespace).Field.toModel} */ toModel(name: string, tableData: Table.AttributeValuesMap, modelData: Model.ModelData, context: ModelContext): void; /** @inheritDoc {@inheritDoc (Fields:namespace).Field.toTable} */ toTable(name: string, modelData: Model.ModelData, tableData: Table.AttributeValuesMap, context: TableContext): void; /** @inheritDoc {@inheritDoc (Fields:namespace).Field.toTableUpdate} */ toTableUpdate(name: string, modelData: Model.ModelUpdate, tableData: Update.ResolverMap, context: TableContext): void; /** * Helper method that just calls {@link Condition.size} with tableName() as path param. * See {@link Condition.size} for more info and examples. */ size(): Condition.ValueResolver; } /** * See {@link Fields.date} for details. */ export class FieldDate extends FieldBase { /** @inheritDoc {@inheritDoc (Fields:namespace).Field.toModel} */ toModel(name: string, tableData: Table.AttributeValuesMap, modelData: Model.ModelData, context: ModelContext): void; /** @inheritDoc {@inheritDoc (Fields:namespace).Field.toTable} */ toTable(name: string, modelData: Model.ModelData, tableData: Table.AttributeValuesMap, context: TableContext): void; /** @inheritDoc {@inheritDoc (Fields:namespace).Field.toTableUpdate} */ toTableUpdate(name: string, modelData: Model.ModelUpdate, tableData: Update.ResolverMap, context: TableContext): void; } /** * See {@link Fields.hidden} for details. * Hidden property field. Used to avoid writing a property to the DynamoDb table. */ export class FieldHidden implements Fields.Field { /** @inheritDoc {@inheritDoc (Fields:namespace).Field.init} */ init(name: string, model: Model): void; /** @inheritDoc {@inheritDoc (Fields:namespace).Field.toModel} */ toModel(name: string, tableData: Table.AttributeValuesMap, modelData: Model.ModelData, context: ModelContext): void; /** @inheritDoc {@inheritDoc (Fields:namespace).Field.toTable} */ toTable(name: string, modelData: Model.ModelData, tableData: Table.AttributeValuesMap, context: TableContext): void; /** @inheritDoc {@inheritDoc (Fields:namespace).Field.toTableUpdate} */ toTableUpdate(name: string, modelData: Model.ModelUpdate, tableData: Update.ResolverMap, context: Fields.TableContext): void; } /** * Composite slot property field, comes from the call to createSlots on FieldCompositeSlot. */ export class FieldCompositeSlot implements Field { /** * Model name of the field, set by init function in Model or Field constructor. */ name?: string; /** * Composite object used to determine some functionality like delimiter. */ composite: FieldComposite; /** * Index number of this slot in the slots array. */ slot: number; /** * All of the slots for the composite field of a model. */ slots: FieldCompositeSlot[]; /** * Initializes this class the required parameters. * @param composite - Composite object used to determine some functionality like delimiter. * @param slot - Index number of this slot in the slots array. * @param slots - All of the slots for the composite field of a model. */ constructor(composite: FieldComposite, slot: number, slots: FieldCompositeSlot[]); /** @inheritDoc {@inheritDoc (Fields:namespace).Field.init} */ init(name: string, model: Model): void; /** @inheritDoc {@inheritDoc (Fields:namespace).Field.toModel} */ toModel(name: string, tableData: Table.AttributeValuesMap, modelData: Model.ModelData, context: ModelContext): void; /** @inheritDoc {@inheritDoc (Fields:namespace).Field.toTable} */ toTable(name: string, modelData: Model.ModelData, tableData: Table.AttributeValuesMap, context: TableContext): void; /** @inheritDoc {@inheritDoc (Fields:namespace).Field.toTableUpdate} */ toTableUpdate(name: string, modelData: Model.ModelUpdate, tableData: Update.ResolverMap, context: TableContext): void; } /** * Options to construct FieldComposite with. */ export interface CompositeOptions { /** * Table attribute name to map this model property to. */ alias: string; /** * Number of model fields (slots) to compose together into a table attribute. */ count?: number; /** * Delimiter to use for when splitting the table attribute in to multiple model fields. */ delimiter?: string; } /** * See {@link Fields.composite} for details. */ export class FieldComposite { /** * Table attribute name to map this model property to. */ alias: string; /** * Number of model fields (slots) to compose together into a table attribute. * @defaultValue 2 */ count: number; /** * Delimiter to use for when splitting the table attribute in to multiple model fields. * @defaultValue ';' */ delimiter: string; /** * Initializes the class with options. * @param options - Options to initialize this class with. */ constructor(options: CompositeOptions); /** * Create the field slots to use when defining the schema for a model. * Note: Need to create a new set of field slots for each model that uses this composite definition. * @returns An array of composite slots used for a Model schema. */ createSlots(): FieldCompositeSlot[]; } /** * Defines the map for the named slots for a composite named field. */ export type CompositeSlotMap = V & { [P in keyof T]: FieldCompositeSlot; }; /** * Options used when constructing a FieldCompositeNamed. */ export interface CompositeNamedOptions extends CompositeOptions { /** * The mapping between the slot name and its index. */ map: T; } /** * See {@link Fields.compositeNamed} for details. */ export class FieldCompositeNamed extends FieldComposite { /** * The mapping between the slot name and its index. */ map: T; /** * Initializes this class with options. * @param options - Options to initialize class with. */ constructor(options: CompositeNamedOptions); /** * Create the named field slots to use when defining the schema for a model. * Note: Need to create a new set of field slots for each model that uses this composite definition. * @returns A map of composite slot fields used in the definition of a Model schema. */ createNamedSlots(): CompositeSlotMap; } /** * Options to construct FieldSplit with. */ export interface SplitOptions { /** * Array of table attribute names to map this model property to. */ aliases: string[]; /** * Delimiter to use for splitting the model property string. */ delimiter?: string; } /** * See {@link Fields.split} for details. * Note: Currently only supports string table attributes. */ export class FieldSplit implements Field { /** * Model name of the field, set by init function in Model or Field constructor. */ name?: string; /** * Array of table attribute names to map this model property to. */ aliases: string[]; /** * Delimiter to use for splitting the model property string, default delimiter is '.'. */ delimiter: string; /** * Initialize this class with options. * @param options - Options to initialize this class with. */ constructor(options: SplitOptions); /** @inheritDoc {@inheritDoc (Fields:namespace).Field.init} */ init(name: string, model: Model): void; /** @inheritDoc {@inheritDoc (Fields:namespace).Field.toModel} */ toModel(name: string, tableData: Table.AttributeValuesMap, modelData: Model.ModelData, context: ModelContext): void; /** @inheritDoc {@inheritDoc (Fields:namespace).Field.toTable} */ toTable(name: string, modelData: Model.ModelData, tableData: Table.AttributeValuesMap, context: TableContext): void; /** @inheritDoc {@inheritDoc (Fields:namespace).Field.toTableUpdate} */ toTableUpdate(name: string, modelData: Model.ModelUpdate, tableData: Update.ResolverMap, context: TableContext): void; } /** * FieldType constructor options. */ export interface TypeOptions { /** * Table attribute to map this Model property to. */ alias?: string; } /** * See {@link Fields."type"} for details. */ export class FieldType implements Field { /** * Model name of the field, set by init function in Model or Field constructor. */ name?: string; /** * Table attribute to map this Model property to. */ alias?: string; /** * Initialize the Field. * @param type - Name of type. * @param alias - Table attribute name to map this model property to. */ constructor(options?: TypeOptions); /** @inheritDoc {@inheritDoc (Fields:namespace).Field.init} */ init(name: string, model: Model): void; /** @inheritDoc {@inheritDoc (Fields:namespace).Field.toModel} */ toModel(name: string, tableData: Table.AttributeValuesMap, modelData: Model.ModelData, context: Fields.ModelContext): void; /** @inheritDoc {@inheritDoc (Fields:namespace).Field.toTable} */ toTable(name: string, modelData: Model.ModelData, tableData: Table.AttributeValuesMap, context: Fields.TableContext): void; /** @inheritDoc {@inheritDoc (Fields:namespace).Field.toTableUpdate} */ toTableUpdate(name: string, modelData: Model.ModelUpdate, tableData: Update.ResolverMap, context: Fields.TableContext): void; } /** * Options for {@link CreatedDate} class constructor. */ export interface CreatedDateOptions { /** * Table attribute to map this Model property to. */ alias?: string; /** * Function to get the current date. */ now?: () => Date; } /** * See {@link Fields.createdDate} for details. */ export class FieldCreatedDate implements Fields.Field { /** * Model name of the field, set by init function in Model or Field constructor. */ name?: string; /** * Table attribute to map this Model property to. */ alias?: string; /** * Function to get the current date. */ now: () => Date; /** * Initialize this class with options. * @param options - Options to initialize this class with. */ constructor(options?: CreatedDateOptions); /** @inheritDoc {@inheritDoc (Fields:namespace).Field.init} */ init(name: string, model: Model): void; /** @inheritDoc {@inheritDoc (Fields:namespace).Field.toModel} */ toModel(name: string, tableData: Table.AttributeValuesMap, modelData: Model.ModelData, context: Fields.ModelContext): void; /** @inheritDoc {@inheritDoc (Fields:namespace).Field.toTable} */ toTable(name: string, modelData: Model.ModelData, tableData: Table.AttributeValuesMap, context: Fields.TableContext): void; /** @inheritDoc {@inheritDoc (Fields:namespace).Field.toTableUpdate} */ toTableUpdate(name: string, modelData: Model.ModelUpdate, tableData: Update.ResolverMap, context: Fields.TableContext): void; } /** * Options used when creating {@link FieldUpdatedDate} */ export interface UpdateDateOptions { /** * Table attribute to map this Model property to. */ alias?: string; /** * Function to get the current date. */ now?: () => Date; } /** * See {@link Fields.updatedDate} for more details. */ export class FieldUpdatedDate implements Fields.Field { /** * Model name of the field, set by init function in Model or Field constructor. */ name?: string; /** * Table attribute to map this Model property to. */ alias?: string; /** * Function to get the current date. */ now: () => Date; /** * Initialize this class with options. * @param options - Options to initialize this class with. */ constructor(options?: UpdateDateOptions); /** @inheritDoc {@inheritDoc (Fields:namespace).Field.init} */ init(name: string, model: Model): void; /** @inheritDoc {@inheritDoc (Fields:namespace).Field.toModel} */ toModel(name: string, tableData: Table.AttributeValuesMap, modelData: Model.ModelData, context: Fields.ModelContext): void; /** @inheritDoc {@inheritDoc (Fields:namespace).Field.toTable} */ toTable(name: string, modelData: Model.ModelData, tableData: Table.AttributeValuesMap, context: Fields.TableContext): void; /** @inheritDoc {@inheritDoc (Fields:namespace).Field.toTableUpdate} */ toTableUpdate(name: string, modelData: Model.ModelUpdate, tableData: Update.ResolverMap, context: Fields.TableContext): void; } /** * See {@link Fields.createdNumberDate} for more details. */ export class FieldCreatedNumberDate extends FieldNumber { /** * Function to get the current date. */ now: () => Date; /** * Initialize this class with options. * @param options - Options to initialize this class with. */ constructor(options?: CreatedDateOptions); /** @inheritDoc {@inheritDoc (Fields:namespace).Field.toTable} */ toTable(name: string, modelData: Model.ModelData, tableData: Table.AttributeValuesMap, context: Fields.TableContext): void; /** @inheritDoc {@inheritDoc (Fields:namespace).Field.toTableUpdate} */ toTableUpdate(name: string, modelData: Model.ModelUpdate, tableData: Update.ResolverMap, context: Fields.TableContext): void; } /** * Options used when creating {@link FieldUpdatedNumberDate} */ export interface UpdateNumberDateOptions { /** * Table attribute to map this Model property to. */ alias?: string; /** * Function to get the current date. */ now?: () => Date; /** * Sets the updated date when item it put. */ writeOnPut?: boolean; /** * Table attribute to use in toModel when value is not present. */ toModelDefaultAlias?: string; } /** * See {@link Fields.updatedNumberDate} for more details. */ export class FieldUpdatedNumberDate extends FieldNumber { /** * Function to get the current date. */ now: () => Date; /** * Sets the updated date when item it put. */ writeOnPut?: boolean; /** * Table attribute to use in toModel when value is not present. */ toModelDefaultAlias?: string; /** * Initialize this class with options. * @param options - Options to initialize this class with. */ constructor(options?: UpdateNumberDateOptions); /** @inheritDoc {@inheritDoc (Fields:namespace).Field.toModel} */ toModel(name: string, tableData: Table.AttributeValuesMap, modelData: Model.ModelData, context: Fields.ModelContext): void; /** @inheritDoc {@inheritDoc (Fields:namespace).Field.toTable} */ toTable(name: string, modelData: Model.ModelData, tableData: Table.AttributeValuesMap, context: Fields.TableContext): void; /** @inheritDoc {@inheritDoc (Fields:namespace).Field.toTableUpdate} */ toTableUpdate(name: string, modelData: Model.ModelUpdate, tableData: Update.ResolverMap, context: Fields.TableContext): void; } /** * Options used when creating {@link FieldRevision} */ export interface RevisionOptions { /** * Table attribute to map this Model property to. */ alias?: string; /** * Start value for revision. */ start?: number; /** * Require that the revision matches when written to */ matchOnWrite?: boolean; } /** * See {@link Fields.revision} for more details. */ export class FieldRevision implements Fields.Field { /** * Model name of the field, set by init function in Model or Field constructor. */ name?: string; /** * Table attribute to map this Model property to. */ alias?: string; /** * Start value for revision. */ start: number; /** * Require that the revision matches when written to */ matchOnWrite?: boolean; /** * Initialize this class with options. * @param options - Options to initialize this class with. */ constructor(options?: RevisionOptions); /** @inheritDoc {@inheritDoc (Fields:namespace).Field.init} */ init(name: string, model: Model): void; /** @inheritDoc {@inheritDoc (Fields:namespace).Field.toModel} */ toModel(name: string, tableData: Table.AttributeValuesMap, modelData: Model.ModelData, context: Fields.ModelContext): void; /** @inheritDoc {@inheritDoc (Fields:namespace).Field.toTable} */ toTable(name: string, modelData: Model.ModelData, tableData: Table.AttributeValuesMap, context: Fields.TableContext): void; /** @inheritDoc {@inheritDoc (Fields:namespace).Field.toTableUpdate} */ toTableUpdate(name: string, modelData: Model.ModelUpdate, tableData: Update.ResolverMap, context: Fields.TableContext): void; } } /** * Represents either Global Secondary Index (GSI) or Local Secondary Index (LSI) for a table. GSI and LSI can be * validated using {@link validateIndex} or {@link validateIndexes}. * * If you are using TypeScript you can use {@link Index.createIndex} to create an Index with strong typing for the primary key. * This provides strong types for the {@link Index.keySchema} property, {@link Index.queryParams} and {@link Index.scan} methods. * * @example [examples/Index.ts]{@link https://github.com/jasoncraftscode/dynamodb-datamodel/tree/main/examples/Index.ts} * ```typescript * [[include:Index.ts]] * ``` * * See {@link Table} for how to include Indexes into a Table. * @public */ export declare class Index { /** * Name of the table's secondary index, used to set the IndexName for dynamodb scan and query actions. */ name: string; /** * Schema map for the Secondary Index's primary key, in the form of \{ \: \{ keyType: 'HASH' \} \}. */ keySchema: Table.PrimaryKey.KeyTypesMap; /** * Defines how the other attributes for an entity are projected to the index. */ projection: { /** * Only relevant when type is 'INCLUDE', list of the attributes to project to the secondary index. */ attributes?: string[]; /** * Defines what general set of attributes are projected into the secondary index. */ type: Table.ProjectionType; }; /** * The table this index is associated with. Used in {@link queryParams}, {@link scanParams}, {@link query}, and {@link scan}. */ table: Table; /** * The type of this secondary index. */ type: Index.Type; /** * @param params - Initialize the Index's name, keySchema and projection properties. */ constructor(params: Index.IndexParams); /** * Gets the partition key name for the Index. * @returns The name of the primary (or HASH) key. */ getPartitionKey(): string; /** * Gets the sort key name for the Index. * @returns The name of the sort (or RANGE) key, or an empty string if one doesn't exists. */ getSortKey(): string; /** * Add the IndexName to query options. * @param options - Options to add IndexName to. * @returns Query options with the IndexName set to the {@link Index.name}. */ getQueryOptions(options?: Table.QueryOptions): Table.QueryOptions; /** * Add the IndexName to scan options. * @param options - Options to add IndexName to. * @returns Scan options with the IndexName set to the {@link Index.name}. */ getScanOptions(options?: Table.ScanOptions): Table.ScanOptions; /** * Creates the params that can be used when calling the [DocumentClient.query]{@link https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/DynamoDB/DocumentClient.html#query-property} method. * @param key - Primary key with optional KeyCondition to query the secondary index with. * @param options - Used in building the query params. * @returns DynamoDB query method params containing the table, index, key and options. */ queryParams(key: Table.PrimaryKey.KeyQueryMap, options?: Table.QueryOptions): DocumentClient.QueryInput; /** * Creates the params that can be used when calling the [DocumentClient.scan]{@link https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/DynamoDB/DocumentClient.html#scan-property} method. * @param options - Used in building the scan params. * @returns DocumentClient scan method's params containing the table, index and options. */ scanParams(options?: Table.ScanOptions): DocumentClient.ScanInput; /** * Wrapper around [DocumentClient.query]{@link https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/DynamoDB/DocumentClient.html#query-property} * method that uses the index and table properties with the key and options params. * @param key - Primary key with optional KeyCondition to query the secondary index with. * @param options - Used in building the query params. * @returns Promise with the query results, including items fetched. */ query(key: Table.PrimaryKey.KeyQueryMap, options?: Table.QueryOptions): Promise; /** * Wrapper around [DocumentClient.scan]{@link https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/DynamoDB/DocumentClient.html#scan-property} * method that uses the index and table properties with the options param. * @param options - Used in building the scan params. * @returns Promise with the scan results, including items fetched. */ scan(options?: Table.ScanOptions): Promise; } /** * Is also a namespace for scoping Index based interfaces and types. * @public */ export declare namespace Index { /** * Type of secondary index. */ export type Type = 'GLOBAL' | 'LOCAL'; /** * Used in {@link Index."constructor"}. */ export interface IndexParams { /** * Name of the table's secondary index, used to set the IndexName for dynamodb scan and query actions. */ name: string; /** * Schema map for the Secondary Index's primary key, in the form of \{ \: \{ keyType: 'HASH' \} \}. */ keySchema: Table.PrimaryKey.KeyTypesMap; /** * Defines how the other attributes for an entity are projected to the index. */ projection: { /** * Only relevant when type is 'INCLUDE', list of the attributes to project to the secondary index. */ attributes?: string[]; /** * Defines what general set of attributes are projected into the secondary index. */ type: Table.ProjectionType; }; /** * The table this index is associated with. Used in {@link queryParams}, {@link scanParams}, {@link query}, and {@link scan}. */ table: Table; /** * The type of this secondary index. */ type: Index.Type; } /** * Default and Example global secondary index primary key with the generalized compact format of. */ export interface DefaultGlobalIndexKey { /** * Partition key: G#P which represents G = Global + # = index number + P = Partition key. */ G0P: Table.PrimaryKey.PartitionString; /** * Sort key: G#S which represents G = Global + # = index number + S = Sort key. The sort key is optional * to support the sort key as being option for queryParams and query methods. */ G0S?: Table.PrimaryKey.SortString; } /** * Default and Example local secondary index primary key with the generalized compact format of. */ export interface DefaultLocalIndexKey { /** * Partition key: P which is the Table partition key since local secondary indexes are stored in the * same partition as the main table. */ P: Table.PrimaryKey.PartitionString; /** * Sort key: L#S which represents L = Local + # = index number + S = Sort key. The sort key is optional * to support the sort key as being option for queryParams and query methods. */ L0S?: Table.PrimaryKey.SortString; } /** * Index constructor param for the generic form of {@link IndexParams}. * @param KEY - The interface of the index's primary key. */ export interface IndexParamsT extends IndexParams { /** * Generic form of {@link IndexParam.keySchema}. */ keySchema: Table.PrimaryKey.KeyTypesMapT; } /** * Generic form of {@link Index}. * @param KEY - The interface of the index's primary key. */ export interface IndexT extends Index { /** * Generic form of {@link Index.keySchema}. */ keySchema: Table.PrimaryKey.KeyTypesMapT; /** * See Generic form of {@link Index.queryParams}. */ queryParams(key: Table.PrimaryKey.KeyQueryMapT, options?: Table.QueryOptions): DocumentClient.QueryInput; /** * Generic form of {@link Index.query}. */ query(key: Table.PrimaryKey.KeyQueryMapT, options?: Table.QueryOptions): Promise; } /** * Creates the generic form of Index used in TypeScript to get strong typing. * * See {@link Table.createTable} reasoning for having a createTable over support 'new TableT'. * @param params - Index constructor params. */ export function createIndex(params: IndexParamsT): IndexT; } /** * Set of helper methods to build KeyConditionExpressions used in DynamoDB query and scan operations. * All of the condition based methods return a {@link KeyCondition.Resolver} function in the form of * '( name: string, exp: KeyCondition.Expression, type?: T,): string' this allow key conditions to be * composed together and even extended in a very simple way. * * * See [Key Condition Expression]{@link https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/Query.html#Query.KeyConditionExpressions} * for details on how each of the below key comparison operations and functions work. * * * @example [examples/KeyCondition.ts]{@link https://github.com/jasoncraftscode/dynamodb-datamodel/tree/main/examples/KeyCondition.ts}, (imports: [examples/Table.ts]{@link https://github.com/jasoncraftscode/dynamodb-datamodel/tree/main/examples/Table.ts}) * ```typescript * [[include:KeyCondition.ts]] * ``` * @public */ export declare class KeyCondition { /** * General compare key condition used by eq, lt, le, gt, and ge. * @example * ```typescript * // Expands to: '#n0 = :v0 AND #n1 >= :v1' * const key = { * P: 'guid', * S: KeyCondition.compare('>=', 'value') * } * const results = await table.query(key); * ``` * @param T - The type used for the value param. * @param op - Compare operation to use: =, \<, \<=. \> or \>=. * @param value - Value to compare the sort key value against. * @returns Resolver to use when generate key condition expression. */ static compare(op: KeyCondition.CompareOperators, value: T): KeyCondition.Resolver; /** * '=' - Equal condition compares if the sort key value is equal to a value. * @example * ```typescript * // Expands to: '#n0 = :v0 AND #n1 = :v1' * const key = { * P: 'guid', * S: KeyCondition.eq('value') * } * const results = await table.query(key); * ``` * @param T - The type used for the value param. * @param value - Value to check if equal to. * @returns Resolver to use when generate key condition expression. */ static eq(value: T): KeyCondition.Resolver; /** * '\<' - Less then condition compares if the sort key value is less then a value. * @example * ```typescript * // Expands to: '#n0 = :v0 AND #n1 < :v1' * const key = { * P: 'guid', * S: KeyCondition.lt('value') * } * const results = await table.query(key); * ``` * @param T - The type used for the value param. * @param value - Value to check if less then. * @returns Resolver to use when generate key condition expression. */ static lt(value: T): KeyCondition.Resolver; /** * '\<=' - Less then or equal to condition compares if the sort key value is less then or equal to a value. * @example * ```typescript * // Expands to: '#n0 = :v0 AND #n1 <= :v1' * const key = { * P: 'guid', * S: KeyCondition.le('value') * } * const results = await table.query(key); * ``` * @param T - The type used for the value param. * @param value - Value to check if less then or equal to. * @returns Resolver to use when generate key condition expression. */ static le(value: T): KeyCondition.Resolver; /** * '\>' - Greater then condition compares if the sort key value is greater then a value. * @example * ```typescript * // Expands to: '#n0 = :v0 AND #n1 > :v1' * const key = { * P: 'guid', * S: KeyCondition.gt('value') * } * const results = await table.query(key); * ``` * @param T - The type used for the value param. * @param value - Value to check if greater then. * @returns Resolver to use when generate key condition expression. */ static gt(value: T): KeyCondition.Resolver; /** * '\>=' - Greater then or equal to condition compares if the sort key value is greater then or equal to a value. * @example * ```typescript * // Expands to: '#n0 = :v0 AND #n1 >= :v1' * const key = { * P: 'guid', * S: KeyCondition.ge('value') * } * const results = await table.query(key); * ``` * @param T - The type used for the value param. * @param value - Value to check if greater then or equal to. * @returns Resolver to use when generate key condition expression. */ static ge(value: T): KeyCondition.Resolver; /** * 'BETWEEN' - Between key condition compares if the sort key value is between two values. * @example * ```typescript * // Expands to: '#n0 = :v0 AND #n1 BETWEEN :v1 AND :v2' * const key = { * P: 'guid', * S: KeyCondition.between('a', 'z') * } * const results = await table.query(key); * ``` * @param T - The type used for the from and to param. * @param from - Value to check if sort key is greater then and equal to. * @param to - Value to check if sort key is less then and equal to. * @returns Resolver to use when generate key condition expression. */ static between(from: T, to: T): KeyCondition.Resolver; /** * 'begins_with' - Begins with function checks to see if the sort key begins with a string value. * Supported Types: String * @example * ```typescript * // Expands to: '#n0 = :v0 AND begins_with(#n1, :v1)' * const key = { * P: 'guid', * S: KeyCondition.beginsWith('a') * } * const results = await table.query(key); * ``` * @param T - The type used for the value param. * @param value - String to check if the sort key value begins with. * @returns Resolver to use when generate key condition expression. */ static beginsWith(value: string): KeyCondition.Resolver; } /** * Is also a namespace for scoping KeyCondition based interfaces and types. * @public */ export declare namespace KeyCondition { /** * Supported compare based operators for conditions expressions. */ export type CompareOperators = '=' | '<' | '<=' | '>' | '>='; /** * Support operators and functions for condition expressions. */ export type Operators = CompareOperators | 'BETWEEN' | 'begins_with'; /** * Expression object used in the key condition resolver to resolve the key condition to an expression. */ export interface Expression { /** * See {@link ExpressionAttributes.addPath} for details. */ addPath(path: string): string; /** * See {@link ExpressionAttributes.addValue} for details. */ addValue(value: Table.AttributeValues): string; /** * Add key condition expression. * @param condition - Condition expression to add. */ addCondition(condition: string): void; /** * Gets the expression from paths, values and conditions added. * @returns key condition expression to use KeyConditionExpression param. */ getExpression(): string | void; } /** * Resolver function is return by most of the above KeyConditions methods. Returning a function allows key conditions * to easily be composable and extensible. This allows consumers to create higher level key conditions that are composed * of the above primitive key conditions or support any new primitives that AWS would add in the future. * @param T - The type used for the value param. * @param name - Name of the primary key attribute to resolve. * @param exp - Object to get path and value aliases and store conditions array. * @param type - Param to enforce type safety for conditions that only work on certain types. */ export type Resolver = (name: string, exp: Expression, type?: T) => void; /** * String key condition resolver. */ export type StringResolver = KeyCondition.Resolver<'S'>; /** * Number key condition resolver. */ export type NumberResolver = KeyCondition.Resolver<'N'>; /** * Binary key condition resolver. */ export type BinaryResolver = KeyCondition.Resolver<'B'>; /** * Support key condition resolvers. */ export type AttributeResolver = StringResolver | NumberResolver | BinaryResolver; } /** * Object passed down to KeyCondition.Resolver functions to support getting path and value aliases and * provide context to the resolver function to support advanced key condition resolvers. * @public */ export declare class KeyConditionExpression implements KeyCondition.Expression { /** * Object for getting path and value aliases. */ attributes: Table.ExpressionAttributes; /** * Array of conditions expressions. * DynamoDB currently only supports two conditions that with an 'AND' between them. */ conditions: string[]; /** * Initialize KeyConditionExpression with existing or new {@link ExpressionAttributes}. * @param attributes - Object used to get path and value aliases. */ constructor(attributes: Table.ExpressionAttributes); /** * See {@link ExpressionAttributes.addPath} for details. */ addPath(path: string): string; /** * See {@link ExpressionAttributes.addValue} for details. */ addValue(value: Table.AttributeValues): string; /** @inheritDoc {@inheritDoc (KeyCondition:namespace).Expression.addCondition} */ addCondition(condition: string): void; /** @inheritDoc {@inheritDoc (KeyCondition:namespace).Expression.getExpression} */ getExpression(): string | void; /** * Create a key condition expression from a primary key. * @param key - Primary key value to build the expression from. * @param exp - Object used to get path and value aliases and store the key conditions array. * @returns A key condition expression to use for the KeyConditionExpression param. */ static buildExpression(key: Table.PrimaryKey.KeyQueryMap, exp: KeyCondition.Expression): string | void; /** * Helper function to set a 'KeyConditionExpression' value on the params argument if there are conditions to resolve. * @param key - List of conditions to evaluate with AND. * @param exp - Used when evaluation conditions and store the names and values mappings. * @param params - Params used for DocumentClient query methods. * @returns The params argument passed in. */ static addParams(params: { KeyConditionExpression?: string; }, attributes: Table.ExpressionAttributes, key: Table.PrimaryKey.KeyQueryMap): void; } /** * The Model object that wraps access to the DynamoDB table and makes it easy to map table data to * and from model data. * * @example [examples/Model.ts]{@link https://github.com/jasoncraftscode/dynamodb-datamodel/tree/main/examples/Model.ts} (imports: [examples/Table.ts]{@link https://github.com/jasoncraftscode/dynamodb-datamodel/tree/main/examples/Table.ts}) * ```typescript * [[include:Model.ts]] * ``` * * @public */ export declare class Model implements Model.ModelBase { /** * The type name of the model. Used by {@link Fields."type"} to set a type attribute. */ name?: string; /** * Schema to use for mapping data between the model and table data. */ schema: Model.ModelSchema; /** * Table to used for reading and writing model data to dynamodb. */ table: Table; /** * Initialize this class with params. * @param params - Params to initialize this class with. */ constructor(params: Model.ModelParams); /** * Converts table item data to model data. Method called from the in the model methods after reading or * writing data to the table to convert the item and attribute output to model properties. * @param data - Table item data to convert to model data. * @param context - Context used for converting table to model data, passed to each field object. * @returns Model data converted from the table data. */ toModel(data: Table.AttributeValuesMap | undefined, context: Fields.ModelContext): Model.ModelOut; /** * Converts model data to table data. Methods called called from the model methods before reading or * writing data to the table, to convert the model data to the table data. * @param data - Model data to convert to table data. * @param context - Context used for converting model to table data, passed to each field object. * @returns Table data converted from the model data. */ toTable(data: Model.ModelData, context: Fields.TableContext): Model.TableData; /** * Converts model update data to table update data, similar to {@link toTable} but since table updates * supports attribute based update expressions updates are handled differently then other actions. * @param data - Model update data to convert to table update data. * @param context - Context used for converting model to table data, passed to each field object. * @returns Table data converted from the model data. */ toTableUpdate(data: Model.ModelUpdate, context: Fields.TableContext): Model.TableUpdateData; /** * Generate the context used in {@link toModel}, {@link toTable} and {@link toTableUpdate}. * @param action - Type of table item action is currently executing. * @param options - Options used when reading or writing to the table. */ getContext(action: Table.ItemActions, options: Table.WriteOptions, scope?: Fields.ActionScope, conditions?: Condition.Resolver[]): Fields.TableContext; /** * Creates the params that can be used when calling [DocumentClient.get]{@link https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/DynamoDB/DocumentClient.html#get-property}. * @param key - Model key of the item to get. * @param options - Additional optional options to use for get. * @returns Input params for [DocumentClient.get]{@link https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/DynamoDB/DocumentClient.html#get-property}. */ getParams(key: Model.ModelCore, options?: Table.GetOptions): DocumentClient.GetItemInput; /** * Creates the params that can be used when calling [DocumentClient.delete]{@link https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/DynamoDB/DocumentClient.html#delete-property}. * @param key - Model key of the item to delete. * @param options - Additional optional options to use for delete. * @returns Input params for [DocumentClient.delete]{@link https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/DynamoDB/DocumentClient.html#delete-property}. */ deleteParams(key: Model.ModelCore, options?: Table.DeleteOptions): DocumentClient.DeleteItemInput; /** * Creates the params that can be used when calling [DocumentClient.put]{@link https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/DynamoDB/DocumentClient.html#put-property}. * @param item - Model item data to put. * @param options - Additional optional options to use for put. * @returns Input params for [DocumentClient.put]{@link https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/DynamoDB/DocumentClient.html#put-property}. */ putParams(item: Model.ModelCore, options?: Table.PutOptions): DocumentClient.PutItemInput; /** * Creates the params that can be used when calling [DocumentClient.update]{@link https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/DynamoDB/DocumentClient.html#update-property}. * @param item - Model item data or update resolver to update. * @param options - Additional optional options to use for update. * @returns Input params for [DocumentClient.update]{@link https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/DynamoDB/DocumentClient.html#update-property}. */ updateParams(item: Model.ModelUpdate, options?: Table.UpdateOptions): DocumentClient.UpdateItemInput; /** * Wrapper method for [DocumentClient.get]{@link https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/DynamoDB/DocumentClient.html#get-property} method. * That uses the model as input and output. * @param key - Model key of item to get. * @param options - Additional optional options to use for get. * @returns An async promise that contains the model data and the table get result object. */ get(key: Model.ModelCore, options?: Table.GetOptions): Promise; /** * Wrapper method for [DocumentClient.delete]{@link https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/DynamoDB/DocumentClient.html#delete-property} method. * That uses the model as input and output. * @param key - Model key of item to delete. * @param options - Additional optional options to use for delete. * @returns An async promise that contains the model data and the table delete result object. */ delete(key: Model.ModelCore, options?: Table.DeleteOptions): Promise; /** * Adds the model item to the table and ensures it doesn't already exists. * See {@link put} for params details. */ create(data: Model.ModelCore, options?: Table.PutOptions): Promise; /** * Replaces the model item in the table only if it already exists. * See {@link put} for details. */ replace(data: Model.ModelCore, options?: Table.PutOptions): Promise; /** * Wrapper method for [DocumentClient.put]{@link https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/DynamoDB/DocumentClient.html#put-property} method. * That uses the model as input and output. * @param item - Model data of the item to put. * @param options - Additional optional options to use for put. * @returns An async promise that contains the model data and the table put result object. */ put(data: Model.ModelCore, options?: Table.PutOptions): Promise; /** * Wrapper method for [DocumentClient.update]{@link https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/DynamoDB/DocumentClient.html#update-property} method. * That uses the model as input and output. * @param item - Model data of the item to update. * @param options - Additional optional options to use for update. * @returns An async promise that contains the model data and the table update result object. */ update(data: Model.ModelUpdate, options?: Table.UpdateOptions): Promise; /** * Adds a get item by key to a batch get operation. * @param batchGet - BatchGet operation to added this key to. * @param key - Key of item to fetch in BatchGet. * @returns Object to get the resulting item from the BatchGet result. */ addBatchGet(batchGet: Table.BatchGet, key: Model.ModelCore): Model.ModelResult; /** * Adds a delete item by key to a batch write operation. * @param batchWrite - BatchWrite operation to added this key to. * @param key - Key of item to delete in BatchWrite. * @returns Object to get the resulting item from the BatchWrite result. */ addBatchDelete(batchWrite: Table.BatchWrite, key: Model.ModelCore): Model.ModelResult; /** * Adds a put item to a batch write operation. * @param batchWrite - BatchWrite operation to added this key to. * @param item - Item added to the batch write operation. * @returns Object to get the resulting item from the BatchWrite result. */ addBatchPut(batchWrite: Table.BatchWrite, item: Model.ModelData): Model.ModelResult; /** * Adds a get item to a transact get operation. * @param transactGet - TransactGet operation to added this key to. * @param key - Key of item to fetch in BatchGet. * @param itemAttributes - List of attributes to fetch in TransactGet, if this is empty then all item attributes are return. * @returns Object to get the resulting item from the TransactGet result. */ addTransactGet(transactGet: Table.TransactGet, key: Model.ModelCore, itemAttributes?: string[]): Model.ModelResult; /** * Adds an item condition check to a transact write operation. * @param transactWrite - TransactWrite operation to added this item condition check to. * @param key - Key of item to used in condition check. * @param conditions - List of conditions to validate when executing the transact write. * @param returnFailure - Determines what to return on transaction failure. * @returns Object to get the resulting item from the TransactWrite result. */ addTransactCheck(transactWrite: Table.TransactWrite, key: Model.ModelCore, conditions: Condition.Resolver[], returnFailure?: DocumentClient.ReturnValuesOnConditionCheckFailure): Model.ModelResult; /** * Adds an item delete to a transact write operation. * @param transactWrite - TransactWrite operation to added this delete item to. * @param key - Key of item to delete in transact write. * @param conditions - List of conditions to validate when executing the transact write. * @param returnFailure - Determines what to return on transaction failure. * @returns Object to get the resulting item from the TransactWrite result. */ addTransactDelete(transactWrite: Table.TransactWrite, key: Model.ModelCore, conditions?: Condition.Resolver[], returnFailure?: DocumentClient.ReturnValuesOnConditionCheckFailure): Model.ModelResult; /** * Adds an item put to a transact write operation. * @param transactWrite - TransactWrite operation to added this put item to. * @param item - Item to put in the transact write. * @param conditions - List of conditions to validate when executing the transact write. * @param returnFailure - Determines what to return on transaction failure. * @returns Object to get the resulting item from the TransactWrite result. */ addTransactPut(transactWrite: Table.TransactWrite, item: Model.ModelData, conditions?: Condition.Resolver[], returnFailure?: DocumentClient.ReturnValuesOnConditionCheckFailure): Model.ModelResult; /** * Adds an item update to a transact write operation. * @param transactWrite - TransactWrite operation to added this update item to. * @param item - Item to update in transact write. * @param conditions - List of conditions to validate when executing the transact write. * @param returnFailure - Determines what to return on transaction failure. * @returns Object to get the resulting item from the TransactWrite result. */ addTransactUpdate(transactWrite: Table.TransactWrite, item: Model.ModelUpdate, conditions?: Condition.Resolver[], returnFailure?: DocumentClient.ReturnValue): Model.ModelResult; /** * Helper method that splits the table data into a key and item. * @param table - Table used to determine what attributes are keys. * @param data - Table data to split into key and item. * @returns The key, item and raw converted model data. */ static splitTableData(table: Table, data: Table.AttributeValuesMap): Model.TableData; /** * Initializes each field in the schema with the model and associated property name. * @param schema - Model schema to initialize. * @param model - Model to use when initialize each field in the schema. */ static initSchema(schema: Model.ModelSchema, model: Model): void; } /** * Is also a namespace for scoping Model based interfaces and types. * @public * */ export declare namespace Model { /** * Interface used in {@link Field.init}. */ export interface ModelBase { /** * The type name of the model. Used by {@link Fields."type"} to set a type attribute. */ name?: string; /** * Schema to use for mapping data between the model and table data. */ schema: Model.ModelSchema; /** * Table to used for reading and writing model data to dynamodb. */ table: Table; } /** * Types supported by the Model. */ export type ModelType = number | string | boolean | null | object; /** * Item data supported by the Model. */ export type ModelData = { [key: string]: ModelType; }; /** * Data returned from {@link Model.toTable}. */ export interface TableData { /** All item table attributes. */ data: Table.AttributeValuesMap; /** Primary key for item. */ key: Table.PrimaryKey.AttributeValuesMap; /** Rest of the item attributes. */ item?: Table.AttributeValuesMap; } /** * Data returned from {@link Model.toTableUpdate}. */ export interface TableUpdateData { /** All item table update attributes. */ data: Update.ResolverMap; /** Primary key for item. */ key: Table.PrimaryKey.AttributeValuesMap; /** Rest of the item update attributes. */ item?: Update.ResolverMap; } /** * Params used when creating {@link Model}. */ export interface ModelParams { /** * The type name of the model. Used by {@link Fields."type"} to set a type attribute. */ name?: string; /** * Schema to use for mapping data between the model and table data. */ schema: Model.ModelSchema; /** * Table to used for reading and writing model data to dynamodb. */ table: Table; } /** * Model property value used for item updates. */ export type ModelUpdateValue = Extract> | null; /** * Type for the Model schema which contains a Field for each Model property. */ export type ModelSchema = { [key: string]: Fields.Field; }; /** * Model input type used in most Model methods. */ export type ModelCore = { [key: string]: ModelType; }; /** * Model output type used in most Model methods. */ export type ModelOut = { [key: string]: ModelType; }; /** * Model input type used for update Model methods. */ export type ModelUpdate = { [key: string]: ModelUpdateValue; }; /** * Base output type for the Model read/write methods. */ export interface BaseOutput { /** * Model item data read from the table. */ item: ModelOutT; /** * The result of the table read/write. */ result: RESULT; } /** * Return value of {@link Model.get}. */ export interface GetOutput extends BaseOutput { } /** * Return value of {@link Model.create}, {@link Model.replace} and {@link Model.put}. */ export interface PutOutput extends BaseOutput { } /** * Return value of {@link Model.delete}. */ export interface DeleteOutput extends BaseOutput { } /** * Return value of {@link Model.update}. */ export interface UpdateOutput extends BaseOutput { } /** * Type for the ModelT schema which contains a Field for each Model property. */ export type ModelSchemaT = { [P in keyof Required]: Fields.Field; }; /** * Model input type used in most ModelT methods. */ export type ModelCoreT = { [P in keyof T]: Exclude; }; /** * Model output type used in most ModelT methods. */ export type ModelOutT = { [P in keyof T]: Exclude; }; /** * Model input type used for update Model methods. */ export type ModelUpdateT = { [P in keyof Table.Optional]: ModelUpdateValue; } & KEY; /** * Params used when creating {@link ModelT}. * @param KEY - Key part of the model used for get and delete actions. * @param OUTPUT - The model output interface. */ export interface ModelParamsT extends ModelParams { /** * Schema to use for mapping data between the model and table data. */ schema: ModelSchemaT; } /** * Generic version of Model, see {@link Model} for more details. * @param KEY - Key part of the model used for get and delete actions. * @param INPUT - The model input interface used for put and update. * @param OUTPUT - The model output interface. */ export interface ModelT extends Model { /** * Schema to use for mapping data between the model and table data. */ schema: Model.ModelSchemaT; /** @inheritDoc {@inheritDoc (Model:class).toModel} */ toModel(data: Table.AttributeValuesMap): Model.ModelOutT; /** @inheritDoc {@inheritDoc (Model:class).toTable} */ toTable(data: Model.ModelCoreT): Model.TableData; /** @inheritDoc {@inheritDoc (Model:class).toTableUpdate} */ toTableUpdate(data: Model.ModelUpdateT): Model.TableUpdateData; /** @inheritDoc {@inheritDoc (Model:class).getParams} */ getParams(key: Model.ModelCoreT, options?: Table.GetOptions): DocumentClient.GetItemInput; /** @inheritDoc {@inheritDoc (Model:class).deleteParams} */ deleteParams(key: Model.ModelCoreT, options?: Table.DeleteOptions): DocumentClient.DeleteItemInput; /** @inheritDoc {@inheritDoc (Model:class).putParams} */ putParams(data: Model.ModelCoreT, options?: Table.PutOptions): DocumentClient.PutItemInput; /** @inheritDoc {@inheritDoc (Model:class).updateParams} */ updateParams(data: Model.ModelUpdateT, options?: Table.UpdateOptions): DocumentClient.UpdateItemInput; /** @inheritDoc {@inheritDoc (Model:class).get} */ get(key: Model.ModelCoreT, options?: Table.GetOptions): Promise>; /** @inheritDoc {@inheritDoc (Model:class).delete} */ delete(key: Model.ModelCoreT, options?: Table.DeleteOptions): Promise>; /** @inheritDoc {@inheritDoc (Model:class).create} */ create(data: Model.ModelCoreT, options?: Table.PutOptions): Promise>; /** @inheritDoc {@inheritDoc (Model:class).replace} */ replace(data: Model.ModelCoreT, options?: Table.PutOptions): Promise>; /** @inheritDoc {@inheritDoc (Model:class).put} */ put(data: Model.ModelCoreT, options?: Table.PutOptions): Promise>; /** @inheritDoc {@inheritDoc (Model:class).update} */ update(data: Model.ModelUpdateT, options?: Table.UpdateOptions): Promise>; /** @inheritDoc {@inheritDoc (Model:class).addBatchGet} */ addBatchGet(batchGet: Table.BatchGet, key: Model.ModelCoreT): Model.ModelResultT; /** @inheritDoc {@inheritDoc (Model:class).addBatchDelete} */ addBatchDelete(batchWrite: Table.BatchWrite, key: Model.ModelCoreT): Model.ModelResultT; /** @inheritDoc {@inheritDoc (Model:class).addBatchPut} */ addBatchPut(batchWrite: Table.BatchWrite, item: Model.ModelCoreT): Model.ModelResultT; /** @inheritDoc {@inheritDoc (Model:class).addTransactGet} */ addTransactGet(transactGet: Table.TransactGet, key: Model.ModelCoreT, itemAttributes?: string[]): Model.ModelResultT; /** @inheritDoc {@inheritDoc (Model:class).addTransactCheck} */ addTransactCheck(transactWrite: Table.TransactWrite, key: Model.ModelCoreT, conditions: Condition.Resolver[], returnFailure?: DocumentClient.ReturnValuesOnConditionCheckFailure): Model.ModelResultT; /** @inheritDoc {@inheritDoc (Model:class).addTransactDelete} */ addTransactDelete(transactWrite: Table.TransactWrite, key: Model.ModelCoreT, conditions?: Condition.Resolver[], returnFailure?: DocumentClient.ReturnValuesOnConditionCheckFailure): Model.ModelResultT; /** @inheritDoc {@inheritDoc (Model:class).addTransactPut} */ addTransactPut(transactWrite: Table.TransactWrite, item: Model.ModelCoreT, conditions?: Condition.Resolver[], returnFailure?: DocumentClient.ReturnValuesOnConditionCheckFailure): Model.ModelResultT; /** @inheritDoc {@inheritDoc (Model:class).addTransactUpdate} */ addTransactUpdate(transactWrite: Table.TransactWrite, item: Model.ModelUpdateT, conditions?: Condition.Resolver[], returnFailure?: DocumentClient.ReturnValue): Model.ModelResultT; } /** * See {@link Table.createTable} reasoning for having a createTable over support 'new TableT'. * @param KEY - Key part of the model used for get and delete actions. * @param INPUT - The model input interface used for put and update. * @param OUTPUT - The model output interface. * @param params - Options to used when creating Model. */ export function createModel(params: ModelParamsT): Model.ModelT; /** * The object returned from model batch or transact methods that will get the * table item from the results and translate it to a model item. */ export class ModelResult { private tableResult; private model; private key; private context; /** * @param tableResult - he batch or transact object to get the result from. * @param model - Model object used to convert the table item to a model item. * @param key - Key of the item to read or write to. * @param context - Context to pass to the Model.toModel method. */ constructor(tableResult: Table.TableResult, model: Model, key: Table.PrimaryKey.AttributeValuesMap, context: Fields.TableContext); /** * Get the model output value and the associated table item. * @returns The model and table item from the result. */ get(): { item: Model.ModelOut; tableItem: Table.AttributeValuesMap; } | void; } /** * Generic version of the {@link ModelResult} used by {@link ModelT} to allow typescript type validation. */ export interface ModelResultT extends ModelResult { /** @inheritDoc {@inheritDoc (Model:namespace).ModelResult.get} */ get(): { item: Model.ModelOutT; tableItem: Table.AttributeValuesMap; } | void; } } /** * Object that represents the DynamoDB table. * * In most single table designs secondary indexes will be used like in the following example: * @example [examples/Table.ts]{@link https://github.com/jasoncraftscode/dynamodb-datamodel/tree/main/examples/Table.ts} (imports: [examples/Index.ts]{@link https://github.com/jasoncraftscode/dynamodb-datamodel/tree/main/examples/Index.ts}) * ```typescript * [[include:Table.ts]] * ``` * * @public */ export declare class Table { private _client?; private _createClient; /** * Name of the DynamoDB table, used to set the TableName when calling DynamoDB methods. */ name: string; /** * Definition of the attribute types required for table and index primary key and for index projected attributes. * These need to be defined at the table level since the attributes are table wide concept. */ keyAttributes: Table.PrimaryKey.AttributeTypesMap; /** * Schema map for the Table's primary key, in the form of \{ \: \{ keyType: 'HASH' \} \}. */ keySchema: Table.PrimaryKey.KeyTypesMap; /** * Determines how errors should be handled. * The default is to throw on any errors. */ onError: (msg: string) => void; /** * @param params - Initialize the Table's name, attributes, keySchema and index properties. */ constructor(params: Table.TableParams); /** * Gets the DocumentClient associated with this Table, which may mean creating one. * @returns The DocumentClient used for all Table operations. */ get client(): DocumentClient; /** * Gets the partition key name for the Table. * @returns The name of the primary (or HASH) key attribute. */ getPartitionKey(): string; /** * Gets the sort key name for the Table. * @returns The name of the sort (or RANGE) key attribute. */ getSortKey(): string; /** * Wrapper around the [DocumentClient.createSet]{@link https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/DynamoDB/DocumentClient.html#createSet-property} * used by the below create*Set methods to create type safe sets. Choose to leverage DocumentClient * implementation of set to allow DocumentClient to correctly auto convert to DynamoDB's native types. * @param list - Array of items to create the set from. * @param options - Options to pass DocumentClient createSet. */ createSet(list: string[] | number[] | Table.BinaryValue[], options?: DocumentClient.CreateSetOptions): Table.AttributeSetValues; /** * Create a string set from a string array. * @param list - String array to create set from. * @param options - Options to pass DocumentClient createSet. */ createStringSet(list: string[], options?: DocumentClient.CreateSetOptions): Table.StringSetValue; /** * Create a number set from a number array. * @param list - Number array to create set from. * @param options - Options to pass DocumentClient createSet. */ createNumberSet(list: number[], options?: DocumentClient.CreateSetOptions): Table.NumberSetValue; /** * Create a binary set from a binary array. * @param list - Binary array to create set from. * @param options - Options to pass DocumentClient createSet. */ createBinarySet(list: Table.BinaryValue[], options?: DocumentClient.CreateSetOptions): Table.BinarySetValue; /** * Creates the params that can be used when calling [DocumentClient.get]{@link https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/DynamoDB/DocumentClient.html#get-property}. * @param key - Primary key of the item to get. * @param options - Additional optional options to use for get. * @returns Input params for [DocumentClient.get]{@link https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/DynamoDB/DocumentClient.html#get-property}. */ getParams(key: Table.PrimaryKey.AttributeValuesMap, options?: Table.GetOptions): Table.GetInput; /** * Creates the params that can be used when calling [DocumentClient.delete]{@link https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/DynamoDB/DocumentClient.html#delete-property}. * @param key - Primary key of the item to delete. * @param options - Additional optional options to use for delete. * @returns Input params for [DocumentClient.delete]{@link https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/DynamoDB/DocumentClient.html#delete-property}. */ deleteParams(key: Table.PrimaryKey.AttributeValuesMap, options?: Table.DeleteOptions): DocumentClient.DeleteItemInput; /** * Get the condition that is needed to support a specific PutWriteOptions. * @param options - Type of put to get the condition for. * @returns Condition resolver that maps to the PutWriteOptions. */ getPutCondition(options: Table.PutWriteOptions | undefined): Condition.Resolver | void; /** * Creates the params that can be used when calling [DocumentClient.put]{@link https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/DynamoDB/DocumentClient.html#put-property}. * @param key - Primary key of item to put. * @param item - Attributes of the item to put. * @param options - Additional optional options to use for put. * @returns Input params for [DocumentClient.put]{@link https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/DynamoDB/DocumentClient.html#put-property}. */ putParams(key: Table.PrimaryKey.AttributeValuesMap, item?: Table.AttributeValuesMap, options?: Table.PutOptions): DocumentClient.PutItemInput; /** * Creates the params that can be used when calling [DocumentClient.update]{@link https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/DynamoDB/DocumentClient.html#update-property}. * By default this method uses `ReturnValues: 'ALL_NEW'` to return all of the properties for an item, * since many APIs or server code use the updated values in some way. * @param key - Primary key of item to update. * @param item - Attributes of the item to update. * @param options - Additional optional options to use for update. * @returns Input params for [DocumentClient.update]{@link https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/DynamoDB/DocumentClient.html#update-property}. */ updateParams(key: Table.PrimaryKey.AttributeValuesMap, item?: Update.ResolverMap, options?: Table.UpdateOptions): DocumentClient.UpdateItemInput; /** * Creates the params that can be used when calling [DocumentClient.query]{@link https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/DynamoDB/DocumentClient.html#query-property} method. * @param key - Primary key with optional KeyCondition to query the table with. * @param options - Used in building the query params. * @returns Input params for [DocumentClient.query]{@link https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/DynamoDB/DocumentClient.html#query-property}. */ queryParams(key: Table.PrimaryKey.KeyQueryMap, options?: Table.QueryOptions): DocumentClient.QueryInput; /** * Creates the params that can be used when calling [DocumentClient.scan]{@link https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/DynamoDB/DocumentClient.html#scan-property} method. * @param options - Used in building the scan params. * @returns Input params for [DocumentClient.scan]{@link https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/DynamoDB/DocumentClient.html#scan-property} method. */ scanParams(options?: Table.ScanOptions): DocumentClient.ScanInput; /** * Wrapper method for [DocumentClient.get]{@link https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/DynamoDB/DocumentClient.html#get-property} method. * @param key - Primary key of item to get. * @param options - Additional optional options to use for get. * @returns Async promise returned by [DocumentClient.get]{@link https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/DynamoDB/DocumentClient.html#get-property} method. */ get(key: Table.PrimaryKey.AttributeValuesMap, options?: Table.GetOptions): Promise; /** * Wrapper method for [DocumentClient.delete]{@link https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/DynamoDB/DocumentClient.html#delete-property} method. * @param key - Primary key of item to delete. * @param options - Additional optional options to use for delete. * @returns Async promise returned by [DocumentClient.delete]{@link https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/DynamoDB/DocumentClient.html#delete-property} method. */ delete(key: Table.PrimaryKey.AttributeValuesMap, options?: Table.DeleteOptions): Promise; /** * Wrapper method for [DocumentClient.put]{@link https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/DynamoDB/DocumentClient.html#put-property} method. * @param key - Primary key of item to put. * @param item - Attributes of the item to put. * @param options - Additional optional options to use for put. * @returns Async promise returned by [DocumentClient.put]{@link https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/DynamoDB/DocumentClient.html#put-property} method. */ put(key: Table.PrimaryKey.AttributeValuesMap, items?: Table.AttributeValuesMap, options?: Table.PutOptions): Promise; /** * Wrapper method for [DocumentClient.update]{@link https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/DynamoDB/DocumentClient.html#update-property} method. * @param key - Primary key of item to update. * @param item - Attributes of the item to update. * @param options - Additional optional options to use for update. * @returns Async promise returned by [DocumentClient.update]{@link https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/DynamoDB/DocumentClient.html#update-property} method. */ update(key: Table.PrimaryKey.AttributeValuesMap, item?: Update.ResolverMap, options?: Table.UpdateOptions): Promise; /** * Wrapper around [DocumentClient.query]{@link https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/DynamoDB/DocumentClient.html#query-property}. * method that uses the index and table properties with the key and options params. * @param key - Primary key with optional KeyCondition to query the secondary index with. * @param options - Used in building the query params. * @returns Promise with the query results, including items fetched. */ query(key: Table.PrimaryKey.KeyQueryMap, options?: Table.QueryOptions): Promise; /** * Wrapper around [DocumentClient.scan]{@link https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/DynamoDB/DocumentClient.html#scan-property}. * method that uses the index and table properties with the options param. * @param options - Used in building the scan params. * @returns Promise with the scan results, including items fetched. */ scan(options?: Table.ScanOptions): Promise; /** * Creates the params that can be used when calling [DocumentClient.batchGet]{@link https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/DynamoDB/DocumentClient.html#batchGet-property} method. * @param batchGet - Batch get object to set the table get on. * @param keys - Keys of items to get. * @param options - Set of get options for table. * @returns BatchGet object passed in, to support calling execute on same line. */ setBatchGet(batchGet: Table.BatchGet, keys: Table.PrimaryKey.AttributeValuesMap[], options?: Table.BatchGetTableOptions): Table.BatchGet; /** * Creates the params that can be used when calling [DocumentClient.batchWrite]{@link https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/DynamoDB/DocumentClient.html#batchWrite-property} method. * @param batchWrite - Batch write object to set the table write on. * @param putItems - Items to put in the table. * @param delKeys - Keys of items to delete from the table. * @returns BatchWrite object passed in, to support calling execute on same line. */ setBatchWrite(batchWrite: Table.BatchWrite, putItems?: Table.PutItem[], delKeys?: Table.PrimaryKey.AttributeValuesMap[]): Table.BatchWrite; /** * Creates the params that can be used when calling [DocumentClient.transactGet]{@link https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/DynamoDB/DocumentClient.html#transactGet-property} method. * @param batchWrite - Batch write object to set the table write on. * @param keys - Keys of items to get. * @param getItems - Keys of items and associated attributes to get. * @returns TransactGet object passed in, to support calling execute on same line. */ setTransactGet(transactGet: Table.TransactGet, getItems: Table.TransactGetItem[]): Table.TransactGet; /** * Creates the params that can be used when calling [DocumentClient.transactWrite]{@link https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/DynamoDB/DocumentClient.html#transactWrite-property} method. * @param write - Set of operations to write in the transaction. * @param options - Used in building the transactWrite params. * @returns TransactWrite object passed in, to support calling execute on same line. */ setTransactWrite(transactWrite: Table.TransactWrite, write: Table.TransactWriteData): Table.TransactWrite; /** * Maps PutWriteOptions to one of the put based ItemActions used by Fields to tell the type of put operation. * @param options - Put write option to map into a put item action. */ static getPutAction(options?: Table.PutWriteOptions): Table.PutItemActions; /** * Checks if item action is a put based action. * @param action - Item actions to check if put. * @returns True if item action is a put action. */ static isPutAction(action: Table.ItemActions): boolean; /** * Appends attributes names to the ProjectionExpression for input params. * @param params - Params to add ProjectionExpression on. * @param itemAttributes - List of attribute names to return. * @param attributes - Definition of the attribute types required for table and index primary key and for index projected attributes. * @returns Params that have ProjectionExpression added to. */ static addItemAttributes(params: T, attributes: Table.ExpressionAttributes, itemAttributes?: string[]): void; /** * Add expressions properties to the params object. * @param T - Type of table action input params * @param params - The params object to add expression properties to. * @param options - Options used to build params. * @param addParam - Function to add additional expression params. * @returns Params object that was passed in with expression added. */ static addParams(params: T, options: Table.AddParamsOptions, addParams?: Table.AddExpressionParams, getAttributes?: () => Table.ExpressionAttributes): T & Table.ExpressionParams; /** * Add expressions properties to the params object. * @param T - Type of table transact write item input params * @param params - The params object to add expression properties to. * @param item - Transact write item used to build params. * @param addParam - Function to add additional expression params. * @returns Params object that was passed in with expression added. */ static addWriteParams(params: T, item: { conditions?: Condition.Resolver[]; returnFailure?: DocumentClient.ReturnValuesOnConditionCheckFailure; }, addParams?: Table.AddExpressionParams): T & Table.ExpressionParams; /** * Translates options into batch or transact based input params. * @param options - Common batch or transact options to set on params. * @param params - Input params to set based on options. */ static addBatchParams(options: { token?: DocumentClient.ClientRequestToken; consumed?: DocumentClient.ReturnConsumedCapacity; metrics?: DocumentClient.ReturnItemCollectionMetrics; }, params: { ClientRequestToken?: DocumentClient.ClientRequestToken; ReturnConsumedCapacity?: DocumentClient.ReturnConsumedCapacity; ReturnItemCollectionMetrics?: DocumentClient.ReturnItemCollectionMetrics; }): void; /** * Finds the partition or sort key name for a table or index key schema. * @param keySchema - Table key schema to find the primary key in. * @param type - Primary key type to look for, either HASH or RANGE. * @returns Name of the key if it exists otherwise an empty string. */ static getKeyName(keySchema: Table.PrimaryKey.KeyTypesMap, type: Table.PrimaryKey.KeyTypes): string; } /** * Is also a namespace for scoping Table based interfaces and types. * @public */ export declare namespace Table { /** * TypeScript utility type that constructs a type consisting of all properties of T set to optional. * Does the opposite of [Required]{@link https://www.typescriptlang.org/docs/handbook/utility-types.html#requiredt}. */ export type Optional = { [P in keyof T]?: T[P]; }; /** * Attribute types support by {@link Table} and [DocumentClient]{@link https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/DynamoDB/DocumentClient.html}. */ export type AttributeTypes = 'B' | 'N' | 'S' | 'BOOL' | 'NULL' | 'L' | 'M' | 'BS' | 'NS' | 'SS'; /** * Binary value supported by {@link Table} and [DocumentClient]{@link https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/DynamoDB/DocumentClient.html}. */ export type BinaryValue = DocumentClient.binaryType; /** * String set value supported by {@link Table} and [DocumentClient]{@link https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/DynamoDB/DocumentClient.html}. */ export type StringSetValue = DocumentClient.StringSet; /** * Number set value supported by {@link Table} and [DocumentClient]{@link https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/DynamoDB/DocumentClient.html}. */ export type NumberSetValue = DocumentClient.NumberSet; /** * Binary set value supported by {@link Table} and [DocumentClient]{@link https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/DynamoDB/DocumentClient.html}. */ export type BinarySetValue = DocumentClient.BinarySet; /** * Map value supported by {@link Table} and [DocumentClient]{@link https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/DynamoDB/DocumentClient.html}. */ export type MapValue = { [key: string]: AttributeValues; }; /** * List value supported by {@link Table} and [DocumentClient]{@link https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/DynamoDB/DocumentClient.html}. */ export type ListValue = AttributeValues[]; /** * Supported Table set based values. */ export type AttributeSetValues = StringSetValue | NumberSetValue | BinarySetValue; /** * Supported Table attribute values. */ export type AttributeValues = null | string | number | boolean | BinaryValue | AttributeSetValues | MapValue | ListValue; /** * Supported Table value map used for {@link put} method. */ export type AttributeValuesMap = { [key: string]: AttributeValues; }; /** * Put based item actions, used by {@link Fields} to determine what put based table operation will be executed. */ export type PutItemActions = 'put' | 'put-new' | 'put-replace'; /** * Item actions used by {@link Fields} to determine what table operation will be executed. */ export type ItemActions = 'get' | 'delete' | PutItemActions | 'update' | 'check'; /** * Params used to construct a {@link Table}. */ export interface TableParams { /** * Name of the DynamoDB table, used to set the TableName when calling DynamoDB methods. */ name: string; /** * Definition of the attribute types required for table and index primary key and for index projected attributes. * These need to be defined at the table level since the attributes are table wide concept. */ keyAttributes: Table.PrimaryKey.AttributeTypesMap; /** * Schema map for the Table's primary key, in the form of \{ \: \{ keyType: 'HASH' \} \}. */ keySchema: Table.PrimaryKey.KeyTypesMap; /** * DocumentClient to use in the {@link Table}. Can be a function to support creating the DocumentClient on demand. */ client: DocumentClient | (() => DocumentClient); /** * Determines how errors should be handled. */ onError?: (msg: string) => void; } /** * Contains the primary key type and key type values. Used when definition {@link Table.keyAttributes}, * {@link Table.keySchema} and {@link Index.keySchema} */ export class PrimaryKey { /** * Use for defining string based {@link Table.keyAttributes} */ static readonly StringType: { type: 'S'; }; /** * Use for defining number based {@link Table.keyAttributes} */ static readonly NumberType: { type: 'N'; }; /** * Use for defining binary based {@link Table.keyAttributes} */ static readonly BinaryType: { type: 'B'; }; /** * Use for defining partition (HASH) key {@link Table.keySchema} or {@link Index.keySchema} */ static readonly PartitionKeyType: { keyType: 'HASH'; }; /** * Use for defining sort (RANGE) key {@link Table.keySchema} or {@link Index.keySchema} */ static readonly SortKeyType: { keyType: 'RANGE'; }; } /** * Is also a namespace for scoping PrimaryKey based interfaces and types. * @public * */ export namespace PrimaryKey { /** Support primary key attribute values types. */ export type AttributeValues = string | number | Table.BinaryValue; /** Supported primary key attribute types (see DocumentClient.ScalarAttributeType). */ export type AttributeTypes = 'B' | 'N' | 'S'; /** Supported primary key types. */ export type KeyTypes = 'HASH' | 'RANGE'; /** Definition for partition string. Used for defining the primary key for Tables and Indexes. */ export type PartitionString = string | { type: 'S'; } | { keyType: 'HASH'; }; /** Definition for partition number. Used for defining the primary key for Tables and Indexes. */ export type PartitionNumber = number | { type: 'N'; } | { keyType: 'HASH'; }; /** Definition for partition number. Used for defining the primary key for Tables and Indexes. */ export type PartitionBinary = Table.BinaryValue | { type: 'B'; } | { keyType: 'HASH'; }; /** Definition for sort string. Used for defining the primary key for Tables and Indexes. */ export type SortString = string | { type: 'S'; } | { keyType: 'RANGE'; } | KeyCondition.StringResolver; /** Definition for sort string. Used for defining the primary key for Tables and Indexes. */ export type SortNumber = number | { type: 'N'; } | { keyType: 'RANGE'; } | KeyCondition.NumberResolver; /** Definition for sort string. Used for defining the primary key for Tables and Indexes. */ export type SortBinary = Table.BinaryValue | { type: 'B'; } | { keyType: 'RANGE'; } | KeyCondition.BinaryResolver; /** Definition for the {@link Table.keyAttributes}. */ export type AttributeTypesMap = { [key: string]: { type: AttributeTypes; }; }; /** Definition for the {@link Table.keySchema} and {@link Index.keySchema}. */ export type KeyTypesMap = { [key: string]: { keyType: KeyTypes; }; }; /** * Definition for the key argument used in {@link Table.queryParams}, {@link Table.query}, * {@link Index.query} and {@link Index.queryParams} */ export type KeyQueryMap = { [key: string]: AttributeValues | KeyCondition.AttributeResolver; }; /** * Definition for the key argument used in {@link Table.get}, {@link Table.delete}, {@link Table.put}, * {@link Table.update} and associated Params methods. */ export type AttributeValuesMap = { [key: string]: AttributeValues; }; /** Typed based version of {@link Table.PrimaryKey.AttributeTypesMap} used in {@link Table.TableT}. */ export type AttributeTypesMapT = { [P in keyof Required]: Extract; }; /** Typed based version of {@link Table.PrimaryKey.KeyTypesMap} used in {@link Table.TableT} and {@link Index.IndexT} */ export type KeyTypesMapT = { [P in keyof Required]: Extract; }; /** Typed based version of {@link Table.PrimaryKey.KeyQueryMap} used in {@link Table.TableT} and {@link Index.IndexT} */ export type KeyQueryMapT = { [P in keyof T]: Extract; }; /** Typed based version of {@link Table.PrimaryKey.AttributeValuesMap} used in {@link Table.TableT} */ export type AttributeValuesMapT = { [P in keyof Required]: Extract; }; /** Attribute query value of the primary key for tables and indexes. */ export interface KeyQuery { /** Partition key query value. */ pk: Table.AttributeValues; /** Sort key query value. */ sk?: Table.AttributeValues | KeyCondition.AttributeResolver; } } /** * Interface that allows expressions to get aliases for path and values and store that mapping to then * allow ExpressionAttributeNames and ExpressionAttributeValues to be set on params. */ export interface ExpressionAttributes { /** * Parse an attribute path and adds the names to the expression attribute names and hands back an alias * to use in condition, update, filter, and other expressions. * @param name - Attribute path to get an alias for. * @returns Alias path to use in place of the attribute name. */ addPath(name: string): string; /** * Adds the value to the expression attribute values and hands back an alias * to use in condition, update, filter, and other expressions. * @param value - Value to add to the values map. * @returns Alias to use in place of the attribute value. */ addValue(value: Table.AttributeValues): string; /** Gets the names map to assign to ExpressionAttributeNames. */ getPaths(): ExpressionAttributeNameMap | void; /** Gets the values map to assign to ExpressionAttributeValues. */ getValues(): Table.AttributeValuesMap | void; } /** The ExpressionAttributes params used by dynamodb. */ export type ExpressionAttributeParams = { ExpressionAttributeNames?: ExpressionAttributeNameMap; ExpressionAttributeValues?: Table.AttributeValuesMap; }; /** The set of expression params used by dynamodb. */ export type ExpressionParams = { ConditionExpression?: string; FilterExpression?: string; KeyConditionExpression?: string; UpdateExpression?: string; ProjectionExpression?: string; } & ExpressionAttributeParams; /** Method to add additional expressions to the params. */ export type AddExpressionParams = (params: ExpressionParams, attributes: ExpressionAttributes) => void; /** * Defines what general set of attributes are projected into the secondary index. * @param ALL - All of the attributes of an item are projected into the secondary index. * @param KEYS_ONLY - The table and the secondary index primary keys are projected into the secondary index. */ export type ProjectionType = 'ALL' | 'KEYS_ONLY' | 'INCLUDE'; /** * Input params for [DocumentClient.get]{@link https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/DynamoDB/DocumentClient.html#get-property} * Removes legacy parameters from the type definition, including AttributesToGet. */ export interface GetInput extends Omit { } /** * Input params for [DocumentClient.put]{@link https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/DynamoDB/DocumentClient.html#put-property} * Removes legacy parameters from the type definition, including Expected and ConditionalOperator */ export interface PutInput extends Omit { } /** * Input params for [DocumentClient.delete]{@link https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/DynamoDB/DocumentClient.html#delete-property} * Removes legacy parameters from the type definition, including Expected and ConditionalOperator */ export interface DeleteInput extends Omit { } /** * Input params for [DocumentClient.update]{@link https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/DynamoDB/DocumentClient.html#update-property} * Removes legacy parameters from the type definition, including AttributeUpdates, Expected and ConditionalOperator */ export interface UpdateInput extends Omit { } /** * Input params for [DocumentClient.query]{@link https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/DynamoDB/DocumentClient.html#query-property} * Removes legacy parameters from the type definition, including AttributesToGet, KeyConditions, QueryFilter and ConditionalOperator */ export interface QueryInput extends Omit { } /** * Input params for [DocumentClient.scan]{@link https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/DynamoDB/DocumentClient.html#scan-property} * Removes legacy parameters from the type definition, including AttributesToGet, QueryFilter and ConditionalOperator */ export interface ScanInput extends Omit { } /** * Input per table params for [DocumentClient.batchGet]{@link https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/DynamoDB/DocumentClient.html#batchGet-property} * Removes legacy parameters from the type definition, including AttributesToGet */ export interface BatchGetTableInput extends Omit { } /** * Base options for all table operations like get, put, delete, update and others. */ export interface BaseOptions { /** * Expression attributes to use for resolving conditions and updates. Will be used to generate the * ExpressionAttributeNames and ExpressionAttributeValues params in table operations. */ attributes?: () => Table.ExpressionAttributes; /** * Params to append on to the params that get passed to dynamodb. This does mean these params can * be used to override any of the values generated by Table, so just be careful on what params you pass. */ params?: Optional; /** User defined context that gets passed through to all Fields. */ context?: any; } /** * Options used in the following methods: {@link Table.get}, {@link Table.getParams}, * {@link Model.get} and {@link Model.getParams}. */ export interface GetOptions extends BaseOptions { /** List of attributes to return from table for operation. */ itemAttributes?: string[]; } /** Base options for all table operations like get, put, delete, update and others. */ export interface WriteOptions extends BaseOptions { /** * Array of expression condition resolvers that are joined together with AND, then used as * ConditionExpression or FilterExpression params in table operations. */ conditions?: Condition.Resolver[]; } /** * Options used in the following methods: {@link Table.delete}, {@link Table.deleteParams}, {@link Model.delete} * and {@link Model.deleteParams}. */ export interface DeleteOptions extends WriteOptions { } /** * Put method write options that determine how put will execute. * * - 'Always' - Default put behavior, that will always set the item weather it exists or now. * - 'Exists' - Only set the item if the item already exists, adds * - ConditionExpression="attribute_exists(#pk)", where #pk is the partition key name. * - 'NotExists' - Only set the item if the item does not exist, add * ConditionExpression="attribute_not_exists(#pk)", where #pk is the partition key name. */ export type PutWriteOptions = 'Always' | 'Exists' | 'NotExists'; /** * Options to used for put and putParams methods on {@link Table} and {@link Model}, along with * {@link Model.new} and {@link Model.replace}. */ export interface PutOptions extends WriteOptions { /** Allows put to be conditional based on if the item already exists. */ writeOptions?: PutWriteOptions; } /** * Options used in the following methods: {@link Table.update}, {@link Table.updateParams}, * {@link Model.update} and {@link Model.updateParams}. */ export interface UpdateOptions extends WriteOptions { } /** * Options used in the following methods: {@link Table.query}, {@link Table.queryParams}, * {@link Index.query} and {@link Index.queryParams}. */ export interface QueryOptions extends BaseOptions { /** List of attributes to return from table for operation. */ itemAttributes?: string[]; /** * Filter conditions for filtering out items after the query but before returning. * Note: Items filtered out still consume read capacity. */ filters?: Condition.Resolver[]; } /** * Options used in the following methods: {@link Table.scan}, {@link Table.scanParams}, * {@link Index.scan} and {@link Index.scanParams}. */ export interface ScanOptions extends BaseOptions { /** List of attributes to return from table for operation. */ itemAttributes?: string[]; /** * Filter conditions for filtering out items after the query but before returning. * Note: Items filtered out still consume read capacity. */ filters?: Condition.Resolver[]; } /** Options used in the following methods: {@link Table.batchGet}, {@link Table.batchGetParams}. */ export interface BatchGetOptions extends BaseOptions { /** Returns the ConsumedCapacity for the table operation. */ consumed?: DocumentClient.ReturnConsumedCapacity; } /** Options used in the following methods: {@link Table.batchGet}, {@link Table.batchGetParams}. */ export interface BatchGetTableOptions extends BaseOptions { /** List of attributes to return from table for operation. */ itemAttributes?: string[]; } /** Options used in the following methods: {@link Table.batchWrite}, {@link Table.batchWriteParams}. */ export interface BatchWriteTableOptions extends BaseOptions { /** Returns the ConsumedCapacity for the table operation. */ consumed?: DocumentClient.ReturnConsumedCapacity; /** Returns the ReturnItemCollectionMetrics for the table operation. */ metrics?: DocumentClient.ReturnItemCollectionMetrics; } /** Options used in the following methods: {@link Table.transactGet}, {@link Table.transactGetParams}. */ export interface TransactGetTableOptions extends BaseOptions { /** Returns the ConsumedCapacity for the table operation. */ consumed?: DocumentClient.ReturnConsumedCapacity; } /** Key and item attributes for used when putting and item */ export interface PutItem { /** Primary key of item to put. */ key: Table.PrimaryKey.AttributeValuesMap; /** Attributes of the item to put. */ item?: Table.AttributeValuesMap; } /** Param to transactGet* methods */ export interface TransactGetItem { /** Primary key of items to get. */ key: Table.PrimaryKey.AttributeValuesMap; /** Attributes of the items to get. */ itemAttributes?: string[]; } /** Options used in the following methods: {@link Table.transactWrite}, {@link Table.transactWriteParams}. */ export interface TransactWriteTableOptions extends BaseOptions { /** Token to use for the transact request. */ token?: DocumentClient.ClientRequestToken; /** Returns the ConsumedCapacity for the table operation. */ consumed?: DocumentClient.ReturnConsumedCapacity; /** Returns the ReturnItemCollectionMetrics for the table operation. */ metrics?: DocumentClient.ReturnItemCollectionMetrics; } /** Param to transactWrite* methods that contains the key and items for each operation supported. */ export interface TransactWriteData { /** Transaction based condition check to validate a condition before writing. */ check?: { key: Table.PrimaryKey.AttributeValuesMap; conditions: Condition.Resolver[]; returnFailure?: DocumentClient.ReturnValuesOnConditionCheckFailure; }[]; /** Transaction based delete item. */ delete?: { key: Table.PrimaryKey.AttributeValuesMap; conditions?: Condition.Resolver[]; returnFailure?: DocumentClient.ReturnValuesOnConditionCheckFailure; }[]; /** Transaction based put item. */ put?: { key: Table.PrimaryKey.AttributeValuesMap; item?: Table.AttributeValuesMap; conditions?: Condition.Resolver[]; returnFailure?: DocumentClient.ReturnValuesOnConditionCheckFailure; }[]; /** Transaction based update item. */ update?: { key: Table.PrimaryKey.AttributeValuesMap; item?: Update.ResolverMap; conditions?: Condition.Resolver[]; returnFailure?: DocumentClient.ReturnValue; }[]; } /** Options used in the following methods: {@link Table.addParams}. */ export interface AddParamsOptions extends BaseOptions { /** List of attributes to return from table for operation. */ itemAttributes?: string[]; /** * Array of expression condition resolvers that are joined together with AND, then used as * ConditionExpression or FilterExpression params in table operations. */ conditions?: Condition.Resolver[]; /** * Filter conditions for filtering out items after the query but before returning. * Note: Items filter out still consume read capacity. */ filters?: Condition.Resolver[]; } /** Default and Example table primary key with a generalized compact format. */ export interface DefaultTableKey { /** Table partition key. */ P: PrimaryKey.PartitionString; /** * Table sort key. The sort key is optional to support the sort key as being option for queryParams * and query methods. */ S?: PrimaryKey.SortString; } /** * Table constructor param for the generic form of {@link TableParams}. * @param KEY - Interface of the table's primary key. * @param ATTRIBUTES - The interface or type that has all required attributes, including table * and index primary key and all defined index projected attributes. */ export interface TableParamsT extends TableParams { /** Generic form of {@link TableParam.keyAttributes}. */ keyAttributes: PrimaryKey.AttributeTypesMapT; /** Generic form of {@link TableParam.keySchema}. */ keySchema: PrimaryKey.KeyTypesMapT; } /** Generic form of {@link Table.PutItem}. */ export interface PutItemT extends PutItem { /** Primary key of item to put. */ key: Table.PrimaryKey.AttributeValuesMapT; /** Attributes of the item to put. */ item?: Table.AttributeValuesMap; } /** Generic form of {@link Table.TransactGetItem}. */ export interface TransactGetItemT extends TransactGetItem { /** Keys of items to get. */ key: Table.PrimaryKey.AttributeValuesMapT; /** Attributes of the items to get. */ itemAttributes?: string[]; } /** Generic form of {@link Table.TransactWrite}. */ export interface TransactWriteDataT extends TransactWriteData { /** Generic form of {@link Table.TransactWrite.check}. */ check?: { key: Table.PrimaryKey.AttributeValuesMapT; conditions: Condition.Resolver[]; returnFailure?: DocumentClient.ReturnValuesOnConditionCheckFailure; }[]; /** Generic form of {@link Table.TransactWrite.delete}. */ delete?: { key: Table.PrimaryKey.AttributeValuesMapT; conditions?: Condition.Resolver[]; returnFailure?: DocumentClient.ReturnValuesOnConditionCheckFailure; }[]; /** Generic form of {@link Table.TransactWrite.put}. */ put?: { key: Table.PrimaryKey.AttributeValuesMapT; item?: Table.AttributeValuesMap; conditions?: Condition.Resolver[]; returnFailure?: DocumentClient.ReturnValuesOnConditionCheckFailure; }[]; /** Generic form of {@link Table.TransactWrite.update}. */ update?: { key: Table.PrimaryKey.AttributeValuesMapT; item?: Update.ResolverMap; conditions?: Condition.Resolver[]; returnFailure?: DocumentClient.ReturnValuesOnConditionCheckFailure; }[]; } /** * Generic form of {@link Table}. * @param KEY - The interface of the table's primary key. * @param ATTRIBUTES - The interface or type that has all required attributes, including * table and index primary key and all defined index projected attributes. */ export interface TableT extends Table { /** Generic form of {@link Table.keyAttributes}. */ keyAttributes: Table.PrimaryKey.AttributeTypesMapT; /** Generic form of {@link Table.keySchema}. */ keySchema: Table.PrimaryKey.KeyTypesMapT; /** * See Generic form of {@link Table.getParams}. */ getParams(key: Table.PrimaryKey.AttributeValuesMapT, options?: Table.GetOptions): DocumentClient.GetItemInput; /** See Generic form of {@link Table.deleteParams}. */ deleteParams(key: Table.PrimaryKey.AttributeValuesMapT, options?: Table.DeleteOptions): DocumentClient.DeleteItemInput; /** See Generic form of {@link Table.putParams}. */ putParams(key: Table.PrimaryKey.AttributeValuesMapT, item?: Table.AttributeValuesMap, options?: Table.PutOptions): DocumentClient.PutItemInput; /** See Generic form of {@link Table.updateParams}. */ updateParams(key: Table.PrimaryKey.AttributeValuesMapT, item?: Update.ResolverMap, options?: Table.UpdateOptions): DocumentClient.UpdateItemInput; /** See Generic form of {@link Table.queryParams}. */ queryParams(key: Table.PrimaryKey.KeyQueryMapT, options?: Table.QueryOptions): DocumentClient.QueryInput; /** See Generic form of {@link Table.scanParams}. */ scanParams(options?: Table.ScanOptions): DocumentClient.ScanInput; /** See Generic form of {@link Table.get}. */ get(key: Table.PrimaryKey.AttributeValuesMapT, options?: Table.GetOptions): Promise; /** See Generic form of {@link Table.delete}. */ delete(key: Table.PrimaryKey.AttributeValuesMapT, options?: Table.DeleteOptions): Promise; /** See Generic form of {@link Table.put}. */ put(key: Table.PrimaryKey.AttributeValuesMapT, item?: Table.AttributeValuesMap, options?: Table.PutOptions): Promise; /** See Generic form of {@link Table.update}. */ update(key: Table.PrimaryKey.AttributeValuesMapT, item?: Update.ResolverMap, options?: Table.UpdateOptions): Promise; /** See Generic form of {@link Table.query}. */ query(key: Table.PrimaryKey.KeyQueryMapT, options?: Table.QueryOptions): Promise; /** See Generic form of {@link Table.scan}. */ scan(options?: Table.ScanOptions): Promise; /** See Generic form of {@link Table.setBatchGet}. */ setBatchGet(batchGet: Table.BatchGet, keys: Table.PrimaryKey.AttributeValuesMapT[]): Table.BatchGet; /** See Generic form of {@link Table.setBatchWrite}. */ setBatchWrite(batchWrite: Table.BatchWrite, putItems?: Table.PutItemT[], delKeys?: PrimaryKey.AttributeValuesMapT[]): Table.BatchWrite; /** See Generic form of {@link Table.setTransactGet}. */ setTransactGet(transactGet: Table.TransactGet, items: Table.TransactGetItemT[]): Table.TransactGet; /** See Generic form of {@link Table.setTransactWrite}. */ setTransactWrite(transactWrite: Table.TransactWrite, write: Table.TransactWriteDataT): Table.TransactWrite; } /** * Creates the generic form of {@link Table} used in TypeScript to get strong typing. * * * So you may ask, why have createTable over just using new {@link Table.TableT}? The reason is that since the method * signature is exactly the same (same method names with same params, only typings are more strict) between * TableT and Table there is no need to have TableT class with just a bunch of pass through wrapper methods. * This also makes the {@link Table} TSDocs easier to read without all of the TypeScript Generic types. Same * approach is taken with {@link Index} and {@link Model}. * @param KEY - The interface of the table's primary key. * @param ATTRIBUTES - The interface or type that has all required attributes, including table and index * primary key and all defined index projected attributes. * @param params - Table constructor params. * @returns A new table as TableT. */ export function createTable(params: Table.TableParamsT): Table.TableT; /** Used by ModelResult to get the table item that will be converted to a model item. */ export interface TableResult { /** * Gets the table item from the result of a DocumentClient operation. * @param tableName - Name of table to get item for. * @param key - Key of table item to get. * @returns The table item data. */ getItem(tableName: string, key: Table.PrimaryKey.AttributeValuesMap): Table.AttributeValuesMap | void; } /** * Compare the value of the list of keys between item1 and item2. * @param keys - List of keys to compare between item1 and item2. * @param item1 - Item to compare item2 against. * @param item2 - Item to compare item1 against. * @returns true if the value of the keys of item1 and item2 are equal. */ export function equalMap(keys: string[], item1: { [key: string]: any; }, item2?: { [key: string]: any; }): boolean; /** Creates the params that can be used when calling [DocumentClient.batchGet]{@link https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/DynamoDB/DocumentClient.html#batchGet-property} method. */ export class BatchGet implements TableResult { private reads; private getTableReads; private result?; /** The DocumentClient used for the batch get operations. */ client: DocumentClient; /** Options used in building the batchGet params. */ options: BatchGetOptions; /** * @param client - The DocumentClient used for the batch get operations. * @param options - Options used in building the batchGet params. */ constructor(client: DocumentClient, options?: BatchGetOptions); /** * Sets the keys for items to fetch from a specific table. * @param tableName - Name of table to for batch get. * @param keys - Keys of items to get. * @param options - options to set for the table batch get. */ set(tableName: string, keys: Table.PrimaryKey.AttributeValuesMap[], options?: BatchGetTableOptions): void; /** * Sets the options for a specific table. * @param tableName - Name of table to for batch get. * @param options - options to set for the table batch get. */ setOptions(tableName: string, options: BatchGetTableOptions): void; /** * Add a get item based on key for a specific table. * @param tableName - Name of table to for batch get. * @param keys - Key of item to get. */ addGet(tableName: string, key: Table.PrimaryKey.AttributeValuesMap): void; /** * Creates the params that can be used when calling [DocumentClient.batchGet]{@link https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/DynamoDB/DocumentClient.html#batchGet-property} method. * @returns Input params for [DocumentClient.batchGet]{@link https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/DynamoDB/DocumentClient.html#batchGet-property} method. */ getParams(): DocumentClient.BatchGetItemInput; /** * Wrapper around [DocumentClient.batchGet]{@link https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/DynamoDB/DocumentClient.html#batchGet-property} method. * @returns Promise with the batchGet results, including responses fetched. */ execute(): Promise; /** * The result from the DocumentClient.batchGet executed. * @returns The output of DocumentClient.batchGet. */ getResult(): DocumentClient.BatchGetItemOutput | undefined; /** * Gets the table item from the DocumentClient.batchGet result. * @param tableName - Name of table to get item for. * @param key - Key of table item to get. * @returns The table item data. */ getItem(tableName: string, key: Table.PrimaryKey.AttributeValuesMap): Table.AttributeValuesMap | void; } /** Creates the params that can be used when calling [DocumentClient.batchWrite]{@link https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/DynamoDB/DocumentClient.html#batchWrite-property} method. */ export class BatchWrite implements TableResult { private writes; private getTableWrites; private result?; /** The DocumentClient used for the batch write operations. */ client: DocumentClient; /** Options used in building the batchWrite params. */ options: Table.BatchWriteTableOptions; /** * @param client - The DocumentClient used for the batch write operations. * @param options - Options used in building the batchWrite params. */ constructor(client: DocumentClient, options?: Table.BatchWriteTableOptions); /** * Sets the items to put and delete for a specific table. * @param tableName - Name of table to for batch write. * @param putItems - Items to put in the table. * @param delKeys - Keys of items to delete from the table. */ set(tableName: string, putItems: Table.PutItem[], delKeys: Table.PrimaryKey.AttributeValuesMap[]): void; /** * Adds a put item for a specific table. * @param tableName - Name of table to for batch write. * @param item - Items to put in the table. */ addPut(tableName: string, item: Table.PutItem): void; /** * Adds a delete item by key for a specific table. * @param tableName - Name of table to for batch write. * @param key - Keys of item to delete from the table. */ addDelete(tableName: string, key: Table.PrimaryKey.AttributeValuesMap): void; /** * Creates the params that can be used when calling [DocumentClient.batchWrite]{@link https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/DynamoDB/DocumentClient.html#batchWrite-property} method. * @returns Input params for [DocumentClient.batchWrite]{@link https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/DynamoDB/DocumentClient.html#batchWrite-property} method. */ getParams(): DocumentClient.BatchWriteItemInput; /** * Wrapper around [DocumentClient.batchWrite]{@link https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/DynamoDB/DocumentClient.html#batchWrite-property} method. * @returns Promise with the batchWrite results, including responses fetched. */ execute(): Promise; /** * The result from the DocumentClient.batchWrite executed. * @returns The output of DocumentClient.batchWrite. */ getResult(): DocumentClient.BatchWriteItemOutput | undefined; /** * Gets the table item from the DocumentClient.batchWrite result. * @param tableName - Name of table to get item for. * @param key - Key of table item to get. * @returns The table item data. */ getItem(tableName: string, key: Table.PrimaryKey.AttributeValuesMap): Table.AttributeValuesMap | void; } /** Creates the params that can be used when calling [DocumentClient.transactGet]{@link https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/DynamoDB/DocumentClient.html#transactGet-property} method. */ export class TransactGet implements TableResult { private reads; private getTableReads; private request?; private result?; /** The DocumentClient used for the transact get operations. */ client: DocumentClient; /** Options used in building the transactGet params. */ options: Table.TransactGetTableOptions; /** * @param client - The DocumentClient used for the transact get operations. * @param options - Options used in building the transactGet params. */ constructor(client: DocumentClient, options?: Table.TransactGetTableOptions); /** * Sets the keys for the items to fetch for a specific table. * @param tableName - Name of table to for transact get. * @param items - Keys of items and associated attributes to get. */ set(tableName: string, items: Table.TransactGetItem[]): void; /** * Add a get item based on key for a specific table. * @param tableName - Name of table to for transact get. * @param key - Primary key of items to get. * @param itemAttributes - List of attribute names to return, when not present all attributes will be returned. */ addGet(tableName: string, key: Table.PrimaryKey.AttributeValuesMap, itemAttributes?: string[]): void; /** * Creates the params that can be used when calling [DocumentClient.transactGet]{@link https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/DynamoDB/DocumentClient.html#transactGet-property} method. * @returns Input params for [DocumentClient.transactGet]{@link https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/DynamoDB/DocumentClient.html#transactGet-property} method. */ getParams(): DocumentClient.TransactGetItemsInput; /** * Wrapper around [DocumentClient.transactGet]{@link https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/DynamoDB/DocumentClient.html#transactGet-property} method. * @returns Promise with the transactGet results, including responses fetched. */ execute(): Promise; /** * The result from the DocumentClient.transactGet executed. * @returns The output of DocumentClient.transactGet. */ getResult(): DocumentClient.TransactGetItemsOutput | undefined; /** * Gets the table item from the DocumentClient.transactGet result. * @param tableName - Name of table to get item for. * @param key - Key of table item to get. * @returns The table item data. */ getItem(tableName: string, key: Table.PrimaryKey.AttributeValuesMap): Table.AttributeValuesMap | void; } /** Wrapper around [DocumentClient.transactWrite]{@link https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/DynamoDB/DocumentClient.html#transactWrite-property} method. */ export class TransactWrite implements TableResult { private writes; private getTableWrites; private result?; /** The DocumentClient used for the transact write operations. */ client: DocumentClient; /** Options used in building the transactWrite params. */ options: Table.TransactWriteTableOptions; /** * @param client - The DocumentClient used for the transact write operations. * @param options - Options used in building the transactWrite params. */ constructor(client: DocumentClient, options?: Table.TransactWriteTableOptions); /** * Sets the items to check, delete, put and update for a specific table. * @param tableName - Name of table to for transact write. * @param write - Set of operations to write in the transaction. */ set(tableName: string, writes: Required): void; /** * Add check condition statement to transactWrite. * @param tableName - Name of table for write transaction. * @param key - Key of item to used in condition check. * @param conditions - List of conditions to validate when executing the transact write. * @param returnFailure - Determines what to return on transaction failure. */ addCheck(tableName: string, key: Table.PrimaryKey.AttributeValuesMap, conditions: Condition.Resolver[], returnFailure?: DocumentClient.ReturnValuesOnConditionCheckFailure): void; /** * Add delete statement to transact write. * @param tableName - Name of table for write transaction. * @param key - Key of item to delete in transact write. * @param conditions - List of conditions to validate when executing the transact write. * @param returnFailure - Determines what to return on transaction failure. */ addDelete(tableName: string, key: Table.PrimaryKey.AttributeValuesMap, conditions?: Condition.Resolver[], returnFailure?: DocumentClient.ReturnValuesOnConditionCheckFailure): void; /** * Add put statement to transact write. * @param tableName - Name of table for write transaction. * @param key - Key of item to put in transact write. * @param item - Item to put in the transact write. * @param conditions - List of conditions to validate when executing the transact write. * @param returnFailure - Determines what to return on transaction failure. */ addPut(tableName: string, key: Table.PrimaryKey.AttributeValuesMap, item?: Table.AttributeValuesMap, conditions?: Condition.Resolver[], returnFailure?: DocumentClient.ReturnValuesOnConditionCheckFailure): void; /** * Add update statement to transact write. * @param tableName - Name of table for write transaction. * @param key - Key of item to update in transact write. * @param item - Item to update in transact write. * @param conditions - List of conditions to validate when executing the transact write. * @param returnFailure - Determines what to return on transaction failure. */ addUpdate(tableName: string, key: Table.PrimaryKey.AttributeValuesMap, item?: Update.ResolverMap, conditions?: Condition.Resolver[], returnFailure?: DocumentClient.ReturnValue): void; /** * Creates the params that can be used when calling [DocumentClient.transactWrite]{@link https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/DynamoDB/DocumentClient.html#transactWrite-property} method. * @returns Input params for [DocumentClient.transactWrite]{@link https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/DynamoDB/DocumentClient.html#transactWrite-property} method. */ getParams(): DocumentClient.TransactWriteItemsInput; /** * Wrapper around [DocumentClient.transactWrite]{@link https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/DynamoDB/DocumentClient.html#transactWrite-property} method. * @returns Promise with the batchWrite results, including responses fetched. */ execute(): Promise; /** * The result from the DocumentClient.transactWrite executed. * @returns The output of DocumentClient.transactWrite. */ getResult(): DocumentClient.TransactWriteItemsOutput | undefined; /** * Gets the table item from the DocumentClient.transactWrite result. * @param tableName - Name of table to get item for. * @param key - Key of table item to get. * @returns The table item data. */ getItem(tableName: string, key: Table.PrimaryKey.AttributeValuesMap): Table.AttributeValuesMap | void; } } /** * Set of helper methods used to build UpdateExpression for use in DynamoDB update method. * * @example [examples/Update.Model.ts]{@link https://github.com/jasoncraftscode/dynamodb-datamodel/tree/main/examples/Update.Model.ts} (imports: [examples/Table.ts]{@link https://github.com/jasoncraftscode/dynamodb-datamodel/tree/main/examples/Table.ts}) * ```typescript * [[include:Update.Model.ts]] * ``` * * Using Table (though in most cases you'll use Model): * @example [examples/Update.Table.ts]{@link https://github.com/jasoncraftscode/dynamodb-datamodel/tree/main/examples/Update.Table.ts} (imports: [examples/Table.ts]{@link https://github.com/jasoncraftscode/dynamodb-datamodel/tree/main/examples/Table.ts}) * ```typescript * [[include:Update.Table.ts]] * ``` * * @public */ export declare class Update { /** * Used to reference other attributes for the value argument in Update.* methods. * @example * ```typescript * import { Fields, Model, Update } from 'dynamodb-datamodel'; * * const model = new Model({ * schema: { * id: Fields.split({ aliases: ['P', 'S'] }), * fullName: Fields.string(), * name: Fields.string(), * }, * // ...additional properties like table * }); * * // Sets name attribute to the value of the fullName attribute * // Example: If fullName = 'John Smith', then name would be set to 'John Smith' * model.update({ * id: 'P-GUID.S-0', * name: Update.path('fullName'), * }); * ``` * @param path - Attribute path to resolve and get alias for. * @returns Update function that returns the alias for the path. */ static path(path: string): Update.OperandFunction; /** * Used to reference other attributes for the value argument in Update.* methods. * @example * ```typescript * import { Fields, Model, Update } from 'dynamodb-datamodel'; * * const model = new Model({ * schema: { * id: Fields.split({ aliases: ['P', 'S'] }), * fullName: Fields.string(), * name: Fields.string(), * }, * // ...additional properties like table * }); * * // Sets name attribute to the value of the fullName attribute, if fullName * // attribute doesn't exists then set name attribute to 'User Name'. * model.update({ * id: 'P-GUID.S-0', * name: Update.pathWithDefault('fullName', 'User Name'), * }); * ``` * @param T - Type of default value argument. * @param path - Attribute path to resolve and get alias for. * @param value - The default value to set if the path attribute value does not exist. * @returns Update function that returns the alias for the path. */ static pathWithDefault(path: string, value: T): Update.OperandFunction; /** * Sets the default value for an attribute that does not exist in on the table item. * @example * ```typescript * import { Fields, Model, Update } from 'dynamodb-datamodel'; * * const model = new Model({ * schema: { * id: Fields.split({ aliases: ['P', 'S'] }), * name: Fields.string(), * }, * // ...additional properties like table * }); * * // Set name attribute to 'Default Name' only if it doesn't exists * model.update({ * id: 'P-GUID.S-0', * name: Update.default('Default Name'), * }); * ``` * @param T - Type of default value argument. * @param value - Default value to set if attribute value does not exist. * @returns Update resolver function to set default value. */ static default(value: T): Update.Resolver; /** * Delete the attribute from the table item. Setting an model property to null also deletes the attribute. * @example * ```typescript * import { Fields, Model, Update } from 'dynamodb-datamodel'; * * const model = new Model({ * schema: { * id: Fields.split({ aliases: ['P', 'S'] }), * name: Fields.string(), * }, * // ...additional properties like table * }); * * // Deletes name attribute from item. Could also use "name: null" to do the same thing. * model.update({ * id: 'P-GUID.S-0', * name: Update.del(), * }); * ``` * @returns Update resolver function to delete attribute. */ static del(path?: string): Update.Resolver; /** * Sets the attribute to a new value. Set is the default action for model property not set to a Update.Resolver or null. * @example * ```typescript * import { Fields, Model, Update } from 'dynamodb-datamodel'; * * const model = new Model({ * schema: { * id: Fields.split({ aliases: ['P', 'S'] }), * name: Fields.string(), * }, * // ...additional properties like table * }); * * // Sets name attribute from item. Could also use "name: 'new name'" to do the same thing. * model.update({ * id: 'P-GUID.S-0', * name: Update.set('new name'), * }); * ``` * @param T - Type of value argument to set. * @param value - The value (or attribute reference) to update the item attribute to, will add attribute if not present. * @returns Update resolver function to set attribute to a value. */ static set(value: Update.OperandValue): Update.Resolver; /** * Sets an attribute to the result of an arithmetic expression. Note: The reference attributes must exists * for the update to succeed. Helper method used by {@link inc}, {@link dec}, {@link add} and {@link sub}. * @param left - A value (or reference attribute) used on the left side of the arithmetic expression. * @param op - Operation to use for expression. * @param right - A value (or reference attribute) used on the left side of the arithmetic expression. * @returns Update resolver function to set a number attribute to the result of the arithmetic expression. */ static arithmetic(left: Update.OperandNumber | undefined, op: '+' | '-', right: Update.OperandNumber): Update.Resolver<'N'>; /** * Increments a number based attribute by a certain amount. Note: The attribute that is being incremented * must exist in the table item for this update to succeed. * Supported types: number. * @example * ```typescript * import { Fields, Model, Update } from 'dynamodb-datamodel'; * * const model = new Model({ * schema: { * id: Fields.split({ aliases: ['P', 'S'] }), * count: Fields.number(), * }, * // ...additional properties like table * }); * * // Increments the count attribute by 1 * // Example: If count = 3, then after this update it would be 4 * model.update({ * id: 'P-GUID.S-0', * count: Update.inc(1), * }); * ``` * @param value - A value (or reference attribute) to increment the number attribute by. * @returns Update resolver function to increment the attribute. */ static inc(value: Update.OperandNumber): Update.Resolver<'N'>; /** * Decrements a number based attribute by a certain amount. Note: The attribute that is being decremented * must exist in the table item for this update to succeed. * Supported types: number. * @example * ```typescript * import { Fields, Model, Update } from 'dynamodb-datamodel'; * * const model = new Model({ * schema: { * id: Fields.split({ aliases: ['P', 'S'] }), * count: Fields.number(), * }, * // ...additional properties like table * }); * * // Decrements the count attribute by 2 * // Example: if count = 5, then after this update it would be 3 * model.update({ * id: 'P-GUID.S-0', * count: Update.dec(2), * }); * ``` * @param value - A value (or reference attribute) to decrement the number attribute by. * @returns Update resolver function to decrement the attribute. */ static dec(value: Update.OperandNumber): Update.Resolver<'N'>; /** * Sets an attribute to the result of adding two values. Note: The reference attributes must exists * for the update to succeed. * Supported types: number. * @example * ```typescript * import { Fields, Model, Update } from 'dynamodb-datamodel'; * * const model = new Model({ * schema: { * id: Fields.split({ aliases: ['P', 'S'] }), * base: Fields.number(), * count: Fields.number(), * }, * // ...additional properties like table * }); * * // Sets count attribute to the result of adding 3 to the 'base' attribute * // Example: If base = 5, then after this update count will be 8 * model.update({ * id: 'P-GUID.S-0', * count: Update.add('base', 3), * }); * ``` * @param left - A value (or reference attribute) to using in add operation. * @param right - A value (or reference attribute) to using in add operation. * @returns Update resolver function to set a number attribute to the result of adding two values. */ static add(left: Update.OperandNumber, right: Update.OperandNumber): Update.Resolver<'N'>; /** * Sets an attribute to the result of subtracting two values. Note: The reference attributes must exists * for the update to succeed. * Supported types: number. * @example * ```typescript * import { Fields, Model, Update } from 'dynamodb-datamodel'; * * const model = new Model({ * schema: { * id: Fields.split({ aliases: ['P', 'S'] }), * base: Fields.number(), * count: Fields.number(), * }, * // ...additional properties like table * }); * * // Sets count attribute to the result of subtracting 2 from the 'base' attribute * // Example: If base = 9, then after this update count would be 7 * model.update({ * id: 'P-GUID.S-0', * count: Update.sub('base', 2), * }); * ``` * @param left - A value (or reference attribute) to use on the left side of a subtract operation. * @param right - A value (or reference attribute) to use on the right side of a subtract operation. * @returns Update resolver function to set a number attribute to the result of subtracting two values. */ static sub(left: Update.OperandNumber, right: Update.OperandNumber): Update.Resolver<'N'>; /** * Sets an attribute to the result of joining two lists. * Supported types: list. * @example * ```typescript * import { Fields, Model, Update } from 'dynamodb-datamodel'; * * const model = new Model({ * schema: { * id: Fields.split({ aliases: ['P', 'S'] }), * parents: Fields.list(), * ancestors: Fields.list(), * }, * // ...additional properties like table * }); * * // Sets ancestors attribute to the result of joining the list from the parents attribute with ['grandpa, 'grandma'] * // Example: if parents = ['mom', 'dad'], then after this update ancestors will be ['mom', 'dad', 'grandpa', 'grandma'] * model.update({ * id: 'P-GUID.S-0', * ancestors: Update.join('parents', ['grandpa', 'grandma']), * }); * ``` * @param left - A list (or reference attribute) to add to the start. * @param right - A list (or reference attribute) to add at the end. * @returns Update resolver function to set an attribute to the joining of two lists. */ static join(left?: Update.OperandList, right?: Update.OperandList): Update.Resolver<'L'>; /** * Appends items to the end of an existing list attribute. * Supported types: list. * @example * ```typescript * import { Fields, Model, Update } from 'dynamodb-datamodel'; * * const model = new Model({ * schema: { * id: Fields.split({ aliases: ['P', 'S'] }), * groups: Fields.list(), * }, * // ...additional properties like table * }); * * // Appends 'soccer' and 'tennis' to the end of the list in groups attribute * // Example: If groups = ['baseball', 'swimming'], then after this update it would be ['baseball', 'swimming', 'soccer', 'tennis'] * model.update({ * id: 'P-GUID.S-0', * groups: Update.append(['soccer', 'tennis']), * }); * ``` * @param value - A list (or reference attribute) to append. * @returns Update resolver function to append a list to an attribute. */ static append(value: Update.OperandList): Update.Resolver<'L'>; /** * Prepends items to the beginning of an existing list attribute. * Supported types: list. * @example * ```typescript * import { Fields, Model, Update } from 'dynamodb-datamodel'; * * const model = new Model({ * schema: { * id: Fields.split({ aliases: ['P', 'S'] }), * groups: Fields.list(), * }, * // ...additional properties like table * }); * * // Prepends 'soccer', 'tennis' to the beginning of the list in groups attribute * // Example: If groups = ['baseball', 'swimming'], then after this update it would be ['soccer', 'tennis', 'baseball', 'swimming'] * model.update({ * id: 'P-GUID.S-0', * groups: Update.prepend(['soccer', 'tennis']), * }); * ``` * @param value - A list (or reference attribute) to prepend. * @returns Update resolver function to prepend a list to an attribute. */ static prepend(value: Update.OperandList): Update.Resolver<'L'>; /** * Deletes an array of indices from an list based attribute (the lists are 0 based). * Supported types: list. * @example * ```typescript * import { Fields, Model, Update } from 'dynamodb-datamodel'; * * const model = new Model({ * schema: { * id: Fields.split({ aliases: ['P', 'S'] }), * children: Fields.list(), * }, * // ...additional properties like table * }); * * // Removes the values at the 1st and 2nd index in the children attribute. * // Example: If children = ['john', 'jill', 'bob', 'betty'], then after this update children will be ['john', 'betty'] * model.update({ * id: 'P-GUID.S-0', * children: Update.delIndexes([1, 2]); * }); * ``` * @param indexes - Array of indices (numbered indexes into the list) to delete from the list. * @returns Update resolver function to delete indices in a list based attribute. */ static delIndexes(indexes: number[]): Update.Resolver<'L'>; /** * Sets the values of select indices for list based attribute. * Supported types: list. * @example * ```typescript * import { Fields, Model, Update } from 'dynamodb-datamodel'; * * const model = new Model({ * schema: { * id: Fields.split({ aliases: ['P', 'S'] }), * children: Fields.list(), * }, * // ...additional properties like table * }); * * // Sets the values at the 1st and 2nd index in the children attribute to be 'margret' and 'mathew' respectively * // Example: If children = ['john', 'jill', 'bob', 'betty'], then after this update children will be ['john', 'margret', 'mathew', 'betty'] * model.update({ * id: 'P-GUID.S-0', * children: Update.setIndexes({1: 'margret', 2: 'mathew'}); * }); * ``` * @param indexes - Map of indices with values to set in the list. * @returns Update resolver function to set values for select indices in a list based attribute. */ static setIndexes(values: { [key: number]: Update.OperandValue | undefined; }): Update.Resolver<'L'>; /** * Adds an array of values to a set based attribute (sets are ordered). * Supported types: StringSet, NumberSet or BinarySet. * @example * ```typescript * import { Fields, Model, Update } from 'dynamodb-datamodel'; * * const model = new Model({ * schema: { * id: Fields.split({ aliases: ['P', 'S'] }), * colors: Fields.stringSet(), * }, * // ...additional properties like table * }); * * // Adds 'yellow' and 'red' to the colors attribute * // Example: If colors = ['blue', 'yellow'], then after this update colors will be ['blue', 'red', 'yellow'] * model.update({ * id: 'P-GUID.S-0', * colors: Update.addToSet(model.table.createStringSet(['yellow', 'red'])); * }); * ``` * @param value - Array of values to add. * @returns Update resolver function to add an array of values to a set based attribute. */ static addToSet(value: Table.AttributeSetValues): Update.Resolver<'SS' | 'NS' | 'BS'>; /** * Removes an array of values from a set based attribute (sets are ordered). * Supported types: StringSet, NumberSet or BinarySet. * @example * ```typescript * import { Fields, Model, Update } from 'dynamodb-datamodel'; * * const model = new Model({ * schema: { * id: Fields.split({ aliases: ['P', 'S'] }), * colors: Fields.stringSet(), * }, * // ...additional properties like table * }); * * // Remove 'yellow' and 'red' from the colors attribute * // Example: If colors = ['blue', 'yellow'], then after this update colors will be ['blue'] * model.update({ * id: 'P-GUID.S-0', * colors: Update.removeFromSet(model.table.createStringSet(['yellow', 'red'])); * }); * ``` * @param value - Array of values to remove. * @returns Update resolver function to remove an array of values from a set based attribute. */ static removeFromSet(value: Table.AttributeSetValues): Update.Resolver<'SS' | 'NS' | 'BS'>; /** * Updates the inner attributes of a map based attribute. {@link set} is used to overwrite the entire map attribute, while map updates the attributes * inside of table attribute. Example if an address attribute is set to \{ street: 'One Infinite Loop', city: 'Cupertino', state: 'CA, zip: '95014' \} then * using Update.map(\{street: '1 Apple Park Way'\}) will result in \{ street: '1 Apple Park Way', city: 'Cupertino', state: 'CA, zip: '95014' \}, while * using Update.set(\{street: '1 Apple Park Way'\}) will result in \{ street: '1 Apple Park Way' \}. * Supported types: map. * @example * ```typescript * import { Fields, Model, Update } from 'dynamodb-datamodel'; * * const model = new Model({ * schema: { * id: Fields.split({ aliases: ['P', 'S'] }), * address: Fields.map(), * }, * // ...additional properties like table * }); * * // Update only the street property inside of the address attribute * // Example: If address = { street: 'One Infinite Loop', city: 'Cupertino', state: 'CA, zip: '95014' } then * // after this update address will be { street: '1 Apple Park Way', city: 'Cupertino', state: 'CA, zip: '95014' } * model.update({ * id: 'P-GUID.S-0', * address: Update.map({ * street: '1 Apple Park Way' * }); * }); * ``` * @param map - Map of update values and resolvers to evaluate. * @returns Update resolver function to recursively set the inner attributes of a map based attribute. */ static map(map: Update.ResolverMap): Update.Resolver<'M'>; /** * Typed based version of {@link Update.map}. * @param T - Interface for model. * @param map - The model or resolver to create resolver for. * @returns Update resolver function to remove an array of values from a set based attribute. */ static model(map: Update.ResolverModel): Update.Resolver<'M'>; /** * Map that contains string keys with a Model T for each value. * @param T - Interface for Model interface. * @param map - Map containing the models to change for each key. * @returns Update resolver function to remove an array of values from a set based attribute. */ static modelMap(map: Update.ResolverModelMap): Update.Resolver<'M'>; } /** * Is also a namespace for scoping Update based interfaces and types. * @public */ export declare namespace Update { /** * Expression object used in the update resolver to resolve the update into an expression. */ export interface Expression { /** * See {@link ExpressionAttributes.addPath} for details. */ addPath(path: string): string; /** * See {@link ExpressionAttributes.addValue} for details. */ addValue(value: Table.AttributeValues): string; /** * Add value or resolve value function to get back alias or resolved string. * To allow the value to reference a path, the value needs to be a resolver. * @param value - Value to add or resolve. * @param name - Name used to pass down to the value resolver. * @returns Alias or expression for value to use in expression. */ resolveValue(value: Update.OperandValue, name: string): string; /** * Helper method used in update methods that do not support string attributes, like add or sub. * This then allows string values to act as paths, without having to wrap the path in a resolver. * For strings based attributes, like set, need to use the path() function to wrap the path. * @param value - The value, update resolver or path string to add and get back an alias. * @param name - Name used to pass down to the value resolver. * @returns Alias or expression for value to use in expression. */ resolvePathValue(value: Update.OperandValue, name: string): string; /** * Resolves the key and value for a map or set array. * @param fallback - The default fallback function that resolves the map value. * @param getPath - Function to get the path after checking value for undefined. * @param value - The value of the map key. */ resolveMapValue(fallback: (path: string, value: Table.AttributeValues) => void, getPath: () => string, value?: Update.OperandValue): void; /** * Resolves each key of a map to an Update.Expression. * @param name - Name alias of the parent attribute, prepends each key name * @param map - Map of update values and resolvers to evaluate. */ resolveMap(map: Update.ResolverMap, name?: string): void; /** * Append a `SET` update expression. * @param value - Expression to add to the `SET` array. */ addSet(value: string): void; /** * Append a `REMOVE` update expression. * @param value - Expression to add to the `REMOVE` array. */ addRemove(value: string): void; /** * Append an `ADD` update expression. * @param value - Expression to add to the `ADD` array. */ addAdd(value: string): void; /** * Append an `DELETE` update expression. * @param value - Expression to add to the `DELETE` array. */ addDelete(value: string): void; /** * Helper method to build an UpdateExpression string appending all of the expressions from the * lists that are not empty. * @returns UpdateExpression based string. */ getExpression(): string | void; } /** * Resolver function is return by most of the above key Update methods. Returning a function allows table item updates * to easily be composable and extensible. This allows consumers to create higher level table item update that are composed * of the primitive update expressions or support any new primitives that AWS would add in the future. * @param T - The type used for the value param. * @param name - Name of the item attribute to resolve. * @param exp - Object to get path and value aliases and store update array. * @param type - Param to enforce type safety for update that only work on certain types. */ export type Resolver = (name: string, exp: Update.Expression, type?: T) => void; /** * Type used for generic map based update methods. * @param T - The model interface. */ export type ResolverMapT = { [key: string]: T | Resolver | OperandFunction | undefined; }; /** * Type used for map based update methods. */ export type ResolverMap = ResolverMapT; /** * Resolver for each property of the model * @param T - The model interface. */ export type ResolverModelValue = Extract> | null; /** * Resolver for the overall Model. * @param T - The model interface. */ export type ResolverModel = { [P in keyof Table.Optional]: ResolverModelValue; }; /** * Resolver for the map with string keys and Model values. * @param T - The model interface. */ export type ResolverModelMap = { [key: string]: Update.ResolverModel | null | undefined | Update.Resolver<'M'>; }; /** * Update function return by path and pathWithDefault to support nested resolvers. * @param name - Name of the item attribute to resolve. * @param exp - Object to get path and value aliases and store update array. * @returns The resolved value of the update function. */ export type OperandFunction = (name: string, exp: Update.Expression) => string; /** * Type used for general update methods */ export type OperandValue = T | OperandFunction; /** * Type used for number based update methods. */ export type OperandNumber = OperandValue; /** * Type used for generic list based update methods. */ export type OperandList = OperandValue; /** * String specific update resolver, used to define properties in Model interfaces. */ export type String = string | Update.Resolver<'S'>; /** * Number specific update resolver, used to define properties in Model interfaces. */ export type Number = number | Update.Resolver<'N'>; /** * Binary specific update resolver, used to define properties in Model interfaces. */ export type Binary = Table.BinaryValue | Update.Resolver<'B'>; /** * Boolean specific update resolver, used to define properties in Model interfaces. */ export type Boolean = boolean | Update.Resolver<'BOOL'>; /** * Null specific update resolver, used to define properties in Model interfaces. */ export type Null = null | Update.Resolver<'NULL'>; /** * String Set specific update resolver, used to define properties in Model interfaces. */ export type StringSet = string[] | Table.StringSetValue | Update.Resolver<'SS'>; /** * Number Set specific update resolver, used to define properties in Model interfaces. */ export type NumberSet = number[] | Table.NumberSetValue | Update.Resolver<'NS'>; /** * Binary Set specific update resolver, used to define properties in Model interfaces. */ export type BinarySet = Table.BinaryValue[] | Table.BinarySetValue | Update.Resolver<'BS'>; /** * Wrapper to remove recursive types so model interface properties get output with correct type. */ export type ModelT = { [P in keyof T]: Exclude; }; /** * List specific update resolver, used to define properties in Model interfaces. * @param T - The model interface. */ export type List = ModelT[] | Update.Resolver<'L'>; /** * Map specific update resolver, used to define properties in Model interfaces. * @param T - The model interface. */ export type Map = { [key: string]: ModelT; } | Update.Resolver<'M'>; /** * Map specific update resolver, used to define properties in Model interfaces. * @param T - The model interface. */ export type Model = ModelT | Update.Resolver<'M'>; /** * Map specific update resolver, used to define properties in Model interfaces. * @param T - The model interface. */ export type ModelMap = { [key: string]: ModelT; } | Update.Resolver<'M'>; /** * List specific update resolver, used to define properties in Model interfaces. * @param T - The model interface. */ export type ModelList = ModelT[] | Update.Resolver<'L'>; } /** * Object passed into all Update.Resolver functions to support getting path and value aliases, appending * update conditions to SET, REMOVE, ADD and DELETE update arrays and provide context to the resolver function to * support advanced update resolvers. * @public */ export declare class UpdateExpression implements Update.Expression { /** * Array of SET expressions. */ setList: string[]; /** * Array of REMOVE expressions. */ removeList: string[]; /** * Array of ADD expressions. */ addList: string[]; /** * Array of DELETE expressions. */ deleteList: string[]; /** * Object to support getting path and value aliases. */ attributes: Table.ExpressionAttributes; /** * Initialize UpdateExpression with existing or new {@link ExpressionAttributes}. * @param attributes - Object used to get path and value aliases. */ constructor(attributes: Table.ExpressionAttributes); /** * See {@link ExpressionAttributes.addPath} for details. */ addPath(name: string): string; /** * See {@link ExpressionAttributes.addValue} for details. */ addValue(value: Table.AttributeValues): string; /** @inheritDoc {@inheritDoc (Update:namespace).Expression.resolveValue} */ resolveValue(value: Update.OperandValue, name: string): string; /** @inheritDoc {@inheritDoc (Update:namespace).Expression.resolvePathValue} */ resolvePathValue(value: Update.OperandValue, name: string): string; /** @inheritDoc {@inheritDoc (Update:namespace).Expression.resolveMapValue} */ resolveMapValue(fallback: (path: string, value: Table.AttributeValues) => void, getPath: () => string, value?: Update.OperandValue): void; /** @inheritDoc {@inheritDoc (Update:namespace).Expression.resolveMap} */ resolveMap(map: Update.ResolverMap, name?: string): void; /** @inheritDoc {@inheritDoc (Update:namespace).Expression.addSet} */ addSet(value: string): void; /** @inheritDoc {@inheritDoc (Update:namespace).Expression.addRemove} */ addRemove(value: string): void; /** @inheritDoc {@inheritDoc (Update:namespace).Expression.addAdd} */ addAdd(value: string): void; /** @inheritDoc {@inheritDoc (Update:namespace).Expression.addDelete} */ addDelete(value: string): void; /** @inheritDoc {@inheritDoc (Update:namespace).Expression.getExpression} */ getExpression(): string | void; /** * Helper function that resolves the updateMap and returns an UpdateExpression to use in DocumentClient.update method calls. * @param updateMap - Map of update values and resolvers to evaluate. * @param exp - Used when calling update resolver function to store the names and values mappings and update expressions. * @returns Update expression to use in UpdateExpression for DocumentClient.update method calls. */ static buildExpression(updateMap: Update.ResolverMap, exp: Update.Expression): string | void; /** * Helper function to set a 'UpdateExpression' value on the params argument if there are update expressions to resolve. * @param updateMap - Map of update values and resolvers to evaluate. * @param exp - Used when calling update resolver function to store the names and values mappings and update expressions. * @param params - Params used for DocumentClient update method. * @returns The params argument passed in. */ static addParams(params: { UpdateExpression?: string; }, attributes: Table.ExpressionAttributes, updateMap?: Update.ResolverMap): void; } /** * Validates an {@link Index} for a {@link Table}. * @param index - An index for a Table. * @param names - Name of the other indexes. * @public */ export declare function validateIndex(index: Index, names?: Set): void; /** * Validates an array of {@link Index} for a {@link Table}. * @param indexes - Indexes for a Table. * @public */ export declare function validateIndexes(indexes: Index[]): void; /** * Validates that a {@link Table} is configured correctly. The Table's onError methods is called for any * validation errors. This method should primarily be used in tests to validate the table. * @param KEY - The interface of the table's primary key. * @param ATTRIBUTES - The interface or type that has all required attributes, including table and index primary * key and all defined index projected attributes. * @param table - Table to be validated. * @public */ export declare function validateTable(table: Table.TableT): void; export { }