Skip to content

CON-1508: Decorator based arguments validation approach #105

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

Closed
wants to merge 1 commit into from
Closed
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
46 changes: 46 additions & 0 deletions api/decorators/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
export function IsNotEmpty(
target: any,
methodName: string,
parameterIndex: number
) {
if (!target?.validations) {
target.validations = [];
}

target.validations.push(`${methodName}:${parameterIndex}:${IsNotEmpty.name}`);
}
Comment on lines +1 to +11
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Registers validation for argument (it's not possible to get value of the argument in an argument decorator which is weird)


function IsNotEmptyValidate(
methodName: string,
argumentIndex: number,
argumentValue: any
) {
if (argumentValue === '' || argumentValue === null || argumentValue === undefined) {
throw new Error(`Invalid empty argument at index ${argumentIndex} with "${argumentValue}" value in "${methodName}" method`);
}
}
Comment on lines +13 to +21
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actual validation logic


export function Validate(target: any, propertyName: string, descriptor: TypedPropertyDescriptor<Function>) {
let method = descriptor.value!;

descriptor.value = function (...args: Array<any>) {
if (target?.validations?.length) {
for (const validation of target.validations) {
const [methodName, argumentIndex, validatorName] = validation.split(":");

if (method.name === methodName) {
switch (validatorName) {
case IsNotEmpty.name:
const argumentValue = args[argumentIndex];

IsNotEmptyValidate(methodName, argumentIndex, argumentValue);

break;
}
}
}
Comment on lines +28 to +41
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Walk through registered validations and execute them

}

return method.apply(this, arguments);
};
}
4 changes: 3 additions & 1 deletion api/projects/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import { SmartlingBaseApi } from "../base/index";
import { SmartlingAuthApi } from "../auth/index";
import { Logger } from "../logger";
import { ProjectDto } from "./dto/project-dto";
import { IsNotEmpty, Validate } from "../decorators";

export class SmartlingProjectsApi extends SmartlingBaseApi {
constructor(smartlingApiBaseUrl: string, authApi: SmartlingAuthApi, logger: Logger) {
Expand All @@ -10,7 +11,8 @@ export class SmartlingProjectsApi extends SmartlingBaseApi {
this.entrypoint = `${smartlingApiBaseUrl}/projects-api/v2/projects`;
}

async getProjectDetails(projectId: string): Promise<ProjectDto> {
@Validate
async getProjectDetails(@IsNotEmpty projectId: string): Promise<ProjectDto> {
Comment on lines +14 to +15
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@dimitrystd it's just an example of how it can be used (SUBM api class is in private sdk)

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Looks interesting. Just two concerns:

  • It only works with simple types. If we pass an object of Parameters class then we can't validate it. Or need to write more code.
    Using ! and strict compilation can give us similar results.
  • We implement just another validation package.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We would need to refactor here and there to support strictNullChecks mode.

return await this.makeRequest(
"get",
`${this.entrypoint}/${projectId}`
Expand Down
1 change: 1 addition & 0 deletions index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -103,3 +103,4 @@ export * from "./api/locales/dto/direction";
export * from "./api/locales/dto/word-delimeter";
export * from "./api/locales/params/get-locales-parameters";
export * from "./api/locales/index";
export * from "./api/decorators/index";
21 changes: 21 additions & 0 deletions test/projects.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import sinon from "sinon";
import { SmartlingProjectsApi } from "../api/projects/index";
import { loggerMock, authMock, responseMock } from "./mock";
import { SmartlingAuthApi } from "../api/auth/index";
import assert from "assert";

describe("SmartlingProjectsApi class tests.", () => {
const projectId = "testProjectId";
Expand Down Expand Up @@ -47,5 +48,25 @@ describe("SmartlingProjectsApi class tests.", () => {
}
);
});

describe("IsNotEmpty decorator test", () => {
it("Empty string", async () => {
await assert.rejects(async () => {
await projectsApi.getProjectDetails("")
}, new Error('Invalid empty argument at index 0 with "" value in "getProjectDetails" method'));
});

it("null string", async () => {
await assert.rejects(async () => {
await projectsApi.getProjectDetails(null)
}, new Error('Invalid empty argument at index 0 with "null" value in "getProjectDetails" method'));
});

it("undefined string", async () => {
await assert.rejects(async () => {
await projectsApi.getProjectDetails(undefined)
}, new Error('Invalid empty argument at index 0 with "undefined" value in "getProjectDetails" method'));
});
});
});
});