Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix(save): throw validation error if required key is missing #294

Draft
wants to merge 2 commits into
base: main
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,7 @@
"jest": "^29.6.1",
"lint-staged": "^13.2.3",
"prettier": "^3.0.0",
"reflect-metadata": "^0.2.1",
"semantic-release": "^21.0.7",
"ts-jest": "^29.1.1",
"ts-node": "^10.9.1",
Expand Down
9 changes: 7 additions & 2 deletions src/base-model.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ import Scan from './scan';
import { IUpdateActions, buildUpdateActions, put } from './update-operators';
import ValidationError from './validation-error';
import { PutCommandInput } from '@aws-sdk/lib-dynamodb/dist-types/commands/PutCommand';
import { hashKey, item, rangeKey, validItem, validate } from './decorators';

export type KeyValue = string | number | Buffer | boolean | null;
type SimpleKey = KeyValue;
Expand All @@ -34,10 +35,13 @@ const isComposite = (hashKeys_compositeKeys: Keys): hashKeys_compositeKeys is Co
export default abstract class Model<T> {
protected tableName: string | undefined;

@item
protected item: T | undefined;

@hashKey
protected pk: string | undefined;

@rangeKey
protected sk: string | undefined;

protected documentClient: DynamoDBDocumentClient;
Expand Down Expand Up @@ -188,13 +192,14 @@ export default abstract class Model<T> {
*/
async save(item: T, options?: Partial<PutCommandInput>): Promise<T>;

@validate
async save(
item_options?: T | Partial<PutCommandInput>,
@validItem item_options?: T | Partial<PutCommandInput>,
options?: Partial<PutCommandInput>,
): Promise<T> {
// Handle typescript method overloading
const toSave: T | undefined =
item_options != null && this.isItem(item_options) ? item_options : this.item;
item_options != null ? item_options as T : this.item;
const putOptions: Partial<PutCommandInput> | undefined =
item_options != null && this.isItem(item_options)
? options
Expand Down
98 changes: 98 additions & 0 deletions src/decorators.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,98 @@
import "reflect-metadata";
import joi from 'joi';
import ValidationError from "./validation-error";

const itemParamMetadataKey = Symbol("ItemParam");
const itemPropertyKey = Symbol("ItemProperty");
const pkKey = Symbol('PK');
const skKey = Symbol('SK');

export function hashKey(target: any, key: string) {

Check warning on line 10 in src/decorators.ts

View workflow job for this annotation

GitHub Actions / lint

Unexpected any. Specify a different type

Check warning on line 10 in src/decorators.ts

View workflow job for this annotation

GitHub Actions / test

Unexpected any. Specify a different type
Reflect.defineProperty(target, key, {
get: function () {
return this[pkKey];
},
set: function (newVal: string) {
this[pkKey] = newVal
}
})
}

export function rangeKey(target: any, key: string) {

Check warning on line 21 in src/decorators.ts

View workflow job for this annotation

GitHub Actions / lint

Unexpected any. Specify a different type

Check warning on line 21 in src/decorators.ts

View workflow job for this annotation

GitHub Actions / test

Unexpected any. Specify a different type
Reflect.defineProperty(target, key, {
get: function () {
return this[skKey];
},
set: function (newVal: string) {
this[skKey] = newVal
}
})
}

export function item(target: any, key: string) {

Check warning on line 32 in src/decorators.ts

View workflow job for this annotation

GitHub Actions / lint

Unexpected any. Specify a different type

Check warning on line 32 in src/decorators.ts

View workflow job for this annotation

GitHub Actions / test

Unexpected any. Specify a different type
Reflect.defineProperty(target, key, {
get: function () {
const pk = this[pkKey]
const sk = this[skKey]
const item = this[itemPropertyKey];
validateSchema(pk, sk, item);
return item;
},
set: function (newVal: unknown) {
this[itemPropertyKey] = newVal;
}
})
}

export function validItem(
target: any,

Check warning on line 48 in src/decorators.ts

View workflow job for this annotation

GitHub Actions / lint

Unexpected any. Specify a different type

Check warning on line 48 in src/decorators.ts

View workflow job for this annotation

GitHub Actions / test

Unexpected any. Specify a different type
propertyKey: string,
parameterIndex: number
) {
const existingParameters: number[] =
Reflect.getOwnMetadata(itemParamMetadataKey, target, propertyKey) || [];
existingParameters.push(parameterIndex);
Reflect.defineMetadata(
itemParamMetadataKey,
existingParameters,
target,
propertyKey
);
}

export function validate(
target: any,

Check warning on line 64 in src/decorators.ts

View workflow job for this annotation

GitHub Actions / lint

Unexpected any. Specify a different type

Check warning on line 64 in src/decorators.ts

View workflow job for this annotation

GitHub Actions / test

Unexpected any. Specify a different type
propertyName: string,
descriptor: any

Check warning on line 66 in src/decorators.ts

View workflow job for this annotation

GitHub Actions / lint

Unexpected any. Specify a different type

Check warning on line 66 in src/decorators.ts

View workflow job for this annotation

GitHub Actions / test

Unexpected any. Specify a different type
) {
const original = descriptor.value;
descriptor.value = function (...args: any[]) {

Check warning on line 69 in src/decorators.ts

View workflow job for this annotation

GitHub Actions / lint

Unexpected any. Specify a different type

Check warning on line 69 in src/decorators.ts

View workflow job for this annotation

GitHub Actions / test

Unexpected any. Specify a different type
const pk = this[pkKey]
const sk = this[skKey]
const parameters: number[] = Reflect.getOwnMetadata(
itemParamMetadataKey,
target,
propertyName
);
if (parameters) {
for (const parameter of parameters) {
validateSchema(pk, sk, args[parameter]);
}
}
return original.apply(this, args);
};
}

function validateSchema(pk: string | undefined, sk: string | undefined, item: unknown) {
if (!pk) {
throw new Error('Model error: hash key is not defined on this Model');
}
const schema = joi.object().keys({
[pk]: joi.required(),
...(!!sk && { [sk]: joi.required() })
}).options({ allowUnknown: true })
const { error } = schema.validate(item);
if (error) {
throw new ValidationError('Validation error', error);
}
}
38 changes: 37 additions & 1 deletion test/save.spec.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
import { clearTables } from './hooks/create-tables';
import HashKeyModel from './models/hashkey';
import HashKeyModel, { HashKeyEntity } from './models/hashkey';
import TimeTrackedModel from './models/autoCreatedAt-autoUpdatedAt';
import HashKeyJoiModel from './models/hashkey-joi';
import CompositeKeyModel, { CompositeKeyEntity } from './models/composite-keys';

describe('The save method', () => {
beforeEach(async () => {
Expand Down Expand Up @@ -64,6 +65,41 @@ describe('The save method', () => {
expect((e as Error).message.includes('No item to save')).toBe(true);
}
});
test('should throw an error if the hash keys is missing', async () => {
const foo = new HashKeyModel();
const item = {
string: 'whatever',
stringmap: { foo: 'bar' },
stringset: ['bar, bar'],
number: 43,
bool: true,
list: ['foo', 42],
};
try {
await foo.save(item as unknown as HashKeyEntity);
fail('should throw');
} catch (e) {
expect((e as Error).message.includes('Validation error')).toBe(true);
}
});
test('should throw an error if the range key is missing', async () => {
const foo = new CompositeKeyModel();
const item = {
hashkey: 'bar',
string: 'whatever',
stringmap: { foo: 'bar' },
stringset: ['bar, bar'],
number: 43,
bool: true,
list: ['foo', 42],
};
try {
await foo.save(item as unknown as CompositeKeyEntity);
fail('should throw');
} catch (e) {
expect((e as Error).message.includes('Validation error')).toBe(true);
}
});
test('should throw an error if a Joi schema is specified and validation failed', async () => {
const foo = new HashKeyJoiModel({
hashkey: 'bar',
Expand Down
Loading