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

Use AJV to validate User JSON when getting a User by ID #1464

Draft
wants to merge 4 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
1 change: 1 addition & 0 deletions client/package-lock.json

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

3 changes: 2 additions & 1 deletion client/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@
"@angular/platform-browser": "^17.0.9",
"@angular/platform-browser-dynamic": "^17.0.9",
"@angular/router": "^17.0.9",
"ajv": "^8.12.0",
"rxjs": "~7.8.0",
"tslib": "^2.4.0",
"zone.js": "~0.14.3"
Expand Down Expand Up @@ -60,4 +61,4 @@
"ts-node": "^10.9.2",
"typescript": "^5.2.2"
}
}
}
7 changes: 7 additions & 0 deletions client/src/app/users/user-role.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
import { JTDSchemaType } from "ajv/dist/jtd";

export type UserRole = 'admin' | 'editor' | 'viewer';

export const userRoleSchema: JTDSchemaType<UserRole> = {
enum: ["admin", "editor", "viewer"]
};
25 changes: 17 additions & 8 deletions client/src/app/users/user.service.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,10 @@
import { HttpClient, HttpParams } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { Observable } from 'rxjs';
import { environment } from '../../environments/environment';
import { User, UserRole } from './user';
import { map } from 'rxjs/operators';
import { environment } from '../../environments/environment';
import { User, validateUser } from './user';
import { UserRole } from "./user-role";

/**
* Service that provides the interface for getting information
Expand All @@ -27,7 +28,7 @@ export class UserService {
// of `HttpClient` in the unit tests so they don't have to
// make "real" HTTP calls to a server that might not exist or
// might not be currently running.
constructor(private httpClient: HttpClient) {
constructor(private httpClient: HttpClient | null) {
}

/**
Expand Down Expand Up @@ -65,7 +66,7 @@ export class UserService {
}
// Send the HTTP GET request with the given URL and parameters.
// That will return the desired `Observable<User[]>`.
return this.httpClient.get<User[]>(this.userUrl, {
return this.httpClient!.get<User[]>(this.userUrl, {
params: httpParams,
});
}
Expand All @@ -78,7 +79,15 @@ export class UserService {
*/
getUserById(id: string): Observable<User> {
// The input to get could also be written as (this.userUrl + '/' + id)
return this.httpClient.get<User>(`${this.userUrl}/${id}`);
return this.httpClient!.get<User>(`${this.userUrl}/${id}`)
.pipe(map((user) => {
// Validate that `user` matches the `User` schema.
if (validateUser(user)) {
return user;
} else {
throw new Error('User supplied by the server failed to validate: ' + user);
}
}));
}

/**
Expand All @@ -100,20 +109,20 @@ export class UserService {
// Filter by name
if (filters.name) {
filters.name = filters.name.toLowerCase();
filteredUsers = filteredUsers.filter(user => user.name.toLowerCase().indexOf(filters.name) !== -1);
filteredUsers = filteredUsers.filter(user => user.name.toLowerCase().indexOf(filters.name!) !== -1);
}

// Filter by company
if (filters.company) {
filters.company = filters.company.toLowerCase();
filteredUsers = filteredUsers.filter(user => user.company.toLowerCase().indexOf(filters.company) !== -1);
filteredUsers = filteredUsers.filter(user => user.company.toLowerCase().indexOf(filters.company!) !== -1);
}

return filteredUsers;
}

addUser(newUser: Partial<User>): Observable<string> {
// Send post request to add a new user with the user data as the body.
return this.httpClient.post<{id: string}>(this.userUrl, newUser).pipe(map(res => res.id));
return this.httpClient!.post<{id: string}>(this.userUrl, newUser).pipe(map(res => res.id));
}
}
22 changes: 20 additions & 2 deletions client/src/app/users/user.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,8 @@
import Ajv, { JTDSchemaType } from "ajv/dist/jtd";
import { UserRole, userRoleSchema } from "./user-role";

export interface User {
_id: string;
_id?: string;
name: string;
age: number;
company: string;
Expand All @@ -8,4 +11,19 @@ export interface User {
role: UserRole;
}

export type UserRole = 'admin' | 'editor' | 'viewer';
const userSchema: JTDSchemaType<User> = {
properties: {
name: {type: "string"},
age: {type: "uint8"},
company: {type: "string"},
email: {type: "string"},
role: userRoleSchema
},
optionalProperties: {
_id: {type: "string"},
avatar: {type: "string"},
}
}

const ajv = new Ajv()
export const validateUser = ajv.compile(userSchema)
5 changes: 4 additions & 1 deletion client/tsconfig.json
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,10 @@
"es2020",
"dom"
],
"useDefineForClassFields": false
"useDefineForClassFields": false,
"strictNullChecks": true,
// "strict": true,
"noImplicitAny": true
},
"exclude": ["./cypress.config.ts"],
"angularCompilerOptions": {
Expand Down
Loading