dynamodb-toolbox
Version:
Lightweight and type-safe query builder for DynamoDB and TypeScript.
58 lines (57 loc) • 2.25 kB
JavaScript
import { DynamoDBToolboxError } from '../../../errors/dynamoDBToolboxError.js';
import { BinarySchema } from '../../../schema/binary/schema.js';
import { NumberSchema } from '../../../schema/number/schema.js';
import { StringSchema } from '../../../schema/string/schema.js';
import { TableAction } from '../../../table/index.js';
import { isValidPrimitive } from '../../../utils/validation/isValidPrimitive.js';
export class PrimaryKeyParser extends TableAction {
constructor(table) {
super(table);
}
parse(keyInput) {
const table = this.table;
const { partitionKey, sortKey } = table;
const primaryKey = {};
const partitionKeyValue = keyInput[partitionKey.name];
if (!isValidPrimitive(getKeySchema(partitionKey), partitionKeyValue)) {
throw new DynamoDBToolboxError('actions.parsePrimaryKey.invalidKeyPart', {
message: `Invalid partition key: ${partitionKey.name}`,
path: partitionKey.name,
payload: {
expected: partitionKey.type,
received: partitionKeyValue,
keyPart: 'partitionKey'
}
});
}
primaryKey[partitionKey.name] = partitionKeyValue;
if (sortKey === undefined) {
return primaryKey;
}
const sortKeyValue = keyInput[sortKey.name];
if (!isValidPrimitive(getKeySchema(sortKey), sortKeyValue)) {
throw new DynamoDBToolboxError('actions.parsePrimaryKey.invalidKeyPart', {
message: `Invalid sort key: ${sortKey.name}`,
path: sortKey.name,
payload: {
expected: sortKey.type,
received: sortKeyValue,
keyPart: 'sortKey'
}
});
}
primaryKey[sortKey.name] = sortKeyValue;
return primaryKey;
}
}
PrimaryKeyParser.actionName = 'parsePrimaryKey';
const getKeySchema = (key) => {
switch (key.type) {
case 'number':
return new NumberSchema({ big: true });
case 'string':
return new StringSchema({});
case 'binary':
return new BinarySchema({});
}
};