Skip to content

TS data verification #39

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

Open
wants to merge 38 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
38 commits
Select commit Hold shift + click to select a range
10ef2cb
create userapi skeleton
Plymatea Jun 6, 2022
10dccf8
remove whitespace and excess semicolons
Plymatea Jun 7, 2022
b1faa00
correct whitespace deletion
Plymatea Jun 7, 2022
4768723
privatize assignId method
Plymatea Jun 7, 2022
7c24528
remove more excess semicolons
Plymatea Jun 7, 2022
b8612f6
addUser & getUserById methods funtionality
Plymatea Jun 7, 2022
bcbe986
remove excess semicolon
Plymatea Jun 7, 2022
2c8afe8
add error exceptions to addUser() & getUserById()
Plymatea Jun 7, 2022
ecfeb64
throw error if pre-existing ID is submitted to addUser()
Plymatea Jun 7, 2022
5d8a05f
added specific error objects in when thrown
Plymatea Jun 7, 2022
6918b8e
moved try/catch blocks to console.log statements
Plymatea Jun 7, 2022
e028cd3
funtionality for getUsers, deleteUserById, searchUserByName, searchUs…
Plymatea Jun 8, 2022
4269277
refactor small clarity changes. Return deleted user in delete method
Plymatea Jun 8, 2022
66f5923
WIP test conversion
Plymatea Jun 8, 2022
0e00f9a
move assignId into addUser method and convert to date string at gen
Plymatea Jun 8, 2022
98341f2
Merge branch 'andy-userapi' into testing-branch
Plymatea Jun 8, 2022
f2a55e0
WIP test conversion
Plymatea Jun 8, 2022
0d01bfe
include optional contructor parameter on UserAPI
Plymatea Jun 8, 2022
653a050
Merge branch 'andy-userapi' of https://github.com/olioapps/typescript…
Plymatea Jun 8, 2022
1a8ab11
complete jest test conversion
Plymatea Jun 9, 2022
4670b0c
all tests pass after converting dataset to object
Plymatea Jun 10, 2022
b3e22f1
refactor jest file for readablity
Plymatea Jun 10, 2022
6bb4015
merge to with andy-userapi due to changes from PR
Plymatea Jun 10, 2022
5d398b7
WIP object conversion
Plymatea Jun 10, 2022
9bf77c1
add empty lines between tests for readability.
Plymatea Jun 10, 2022
0ff7bdb
new line at end of file
Plymatea Jun 10, 2022
a9fd79a
convert array dataset to object dataset
Plymatea Jun 10, 2022
841fc66
Merge branch 'andy-userapi' of https://github.com/olioapps/typescript…
Plymatea Jun 10, 2022
1905d8c
refactor deleteUserById() to return object
Plymatea Jun 10, 2022
1518d37
remove console.logs from index.ts
Plymatea Jun 10, 2022
e2241b3
refactored deleteUserById() again
Plymatea Jun 10, 2022
6fd6a6a
update UserAPI methods to have explicit return types
Plymatea Jun 10, 2022
e899327
refactor deleteUserById, DRY
Plymatea Jun 10, 2022
f572a82
add line
Plymatea Jun 10, 2022
b9d6d79
Add TS readonly verifications
Plymatea Jun 13, 2022
c1ce197
changed syntax to ReadonlyArray<> to match conventions
Plymatea Jun 13, 2022
54d8531
add more TS data verification
Plymatea Jun 14, 2022
b77357a
remove excess empty line
Plymatea Jun 14, 2022
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
3 changes: 2 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
node_modules
dist
npm-debug.log
coverage
coverage
/vscode
29 changes: 29 additions & 0 deletions .vscode/launch.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
{
Copy link

Choose a reason for hiding this comment

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

this launch.json file should be listed in your .gitignore file

Copy link
Author

Choose a reason for hiding this comment

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

Done, I don't think I understand git versioning well enough to scrub the file from the git repo history. I did it once on a personal project, but scrubbed the entire repo. I'm afraid I'll screw something up if I try it here.

I did add the /vscode folder the gitignore though.

// Use IntelliSense to learn about possible attributes.
// Hover to view descriptions of existing attributes.
// For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
"version": "0.2.0",
"configurations": [
{
"type": "node",
"name": "vscode-jest-tests.v2",
"request": "launch",
"args": [
"--runInBand",
"--watchAll=false",
"--testNamePattern",
"${jest.testNamePattern}",
"--runTestsByPath",
"${jest.testFile}"
],
"cwd": "${workspaceFolder}",
"console": "integratedTerminal",
"internalConsoleOptions": "neverOpen",
// "disableOptimisticBPs": true,
"program": "${workspaceFolder}/node_modules/.bin/jest",
"windows": {
"program": "${workspaceFolder}/node_modules/jest/bin/jest"
}
}
]
}
114 changes: 109 additions & 5 deletions src/index.test.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,111 @@
//write tests here
import { UserAPI, IUser, IUserRecord } from './index'

describe('Tests will go here!', () => {
it('should pass', () => {
expect(true).toBeTruthy()
const seedUsers: Readonly<IUserRecord> = {
"1": { id: "1", name: "andy", favColor: "blue", age: 247 },
"2": { id: "2", name: "Andy", favColor: "purple", age: 150 },
"3": { id: "3", name: "Sarah", favColor: "Blue", age: 200}
}

describe(UserAPI, () => {
const userAPI = new UserAPI(seedUsers)

it('check that UserAPI is initialized', () => {
expect(userAPI).toBeInstanceOf(UserAPI)
})

describe('getUser()', () => {
const userAPI = new UserAPI(seedUsers)

it("getUsers() returns intitial seed data", () => {
const actual = userAPI.getUsers()
const expected = Object.values(seedUsers)
expect(actual).toEqual(expected)
})
})

describe('addUser()', () => {
const userAPI = new UserAPI(seedUsers)

it('addUser() adds new user to the dataset', () => {
const user: IUser = { name: "Sarah", favColor: "Blue", age: 150 }
const newUser: IUser = userAPI.addUser(user)
const actual: ReadonlyArray<IUser> = userAPI.getUsers()
const expected: ReadonlyArray<IUser> = Object.values({...seedUsers, newUser})
expect(actual).toEqual(expected)
})

it("addUser() throws error when duplicating user info", () => {
const userDuplicate = { name: "andy", favColor: "blue", age: 247 }
const actual= () => {userAPI.addUser(userDuplicate)}
expect(actual).toThrow(Error)
})

it("addUser() throws error supplied with pre-existing user.id", () => {
const userWithId = seedUsers['1']
const actual = () => {userAPI.addUser(userWithId)}
expect(actual).toThrow(Error)
})
})

describe('getUserById()', () => {
const userAPI = new UserAPI(seedUsers)

it('getUserById() returns expected user', () => {
const actual: IUser = userAPI.getUserById("2")
const expected: IUser = seedUsers['2']
expect(actual).toEqual(expected)
})

it('getUserById() throws error if user with id is not found', () => {
const actual = () => userAPI.getUserById("100")
expect(actual).toThrow(ReferenceError)
})
})

describe('deleteUserById()', () => {
const userAPI = new UserAPI(seedUsers)

it('deleteUserById() deletes user with given id', () => {
userAPI.deleteUserById("1")
const actual: ReadonlyArray<IUser> = userAPI.getUsers()
const expected: ReadonlyArray<IUser> = [ seedUsers['2'], seedUsers['3'] ]

expect(actual).toEqual(expected)
})

it('deleteUserById() throws error if user is not found', () => {
const actual = () => {userAPI.deleteUserById("100")}
expect(actual).toThrow(ReferenceError)
})
})

describe('searchUserbyName()', () => {
const userAPI = new UserAPI(seedUsers)

it('searchUserByName() returns all instances of given name, independant of capitals', () => {
const actual: ReadonlyArray<IUser> = userAPI.searchUserByName("Andy")
const expected: ReadonlyArray<IUser>= [ seedUsers['1'], seedUsers['2'] ]
expect(actual).toEqual(expected)
})

it('searchUserByName() throws error if no user is found', () => {
const actual = () => userAPI.searchUserByName("Jessica")
expect(actual).toThrow(ReferenceError)
})
})

describe('searchUserFavoriteColor()', () => {
const userAPI = new UserAPI(seedUsers)

it('searchUserByFavoriteColor() returns all instances users with given fav color, independant of capitals', () => {
const actual: ReadonlyArray<IUser> = userAPI.searchUsersByFavoriteColor("blue")
const expected: ReadonlyArray<IUser> = [ seedUsers['1'], seedUsers['3'] ]
expect(actual).toEqual(expected)
})

it('searchUserByFavoriteColor() throws error if no user is found with given fav color', () => {
const actual = () => userAPI.searchUsersByFavoriteColor("Pink")
expect(actual).toThrow(ReferenceError)
})
})
})
})
81 changes: 80 additions & 1 deletion src/index.ts
Original file line number Diff line number Diff line change
@@ -1 +1,80 @@
//Define class here
export interface IUser {
readonly id?: string
readonly name: string
readonly favColor: string
readonly age: number
}

export type IUserRecord = Record<string, IUser>

export class UserAPI {
private _users: Readonly<IUserRecord>

constructor(seedData: IUserRecord = {}) {
this._users = {...seedData}
}

private _assignId(): string {
const id: Readonly<string> = Date.now().toString() + Math.floor(Math.random()*100)
return id
}

addUser(user: IUser): IUser {
if (user.id) {
throw new SyntaxError("Please resubmit without pre-exisitng ID field.")
}
const result = (Object.values(this._users)).some( existingUser => (
existingUser.name.toLowerCase() === user.name.toLowerCase() &&
existingUser.favColor.toLowerCase() === user.favColor.toLowerCase() &&
existingUser.age === user.age
))

if (result) {
throw new Error("A user with those properties already exists in the database.")
}

const newUser = {...user, id: this._assignId()}
this._users = {...this._users, [newUser.id]: newUser}
return newUser
}

getUserById(id: string): IUser {
if (this._users[id]) {
return this._users[id]
}
throw new ReferenceError(`No user found with id ${id}.`)
}

getUsers(): Array<IUser> {
if (this._users === null || this._users === undefined) {
throw new Error(`User Dataset not found`)
}
return Object.values(this._users)
}

deleteUserById(id: string): IUser {
if (this._users[id]) {
const { [id]: deletedUser, ...rest } = this._users
this._users = {...rest}
return deletedUser
}
throw new ReferenceError(`No user found with id ${id}.`)
}

searchUserByName(name: string): ReadonlyArray<IUser> {
const users = Object.values(this._users).filter( user => user.name.toLowerCase() === name.toLowerCase())

if (users.length) {
return users
}
throw new ReferenceError(`No user found with name ${name}`)
}

searchUsersByFavoriteColor(color: string): ReadonlyArray<IUser> {
const users = Object.values(this._users).filter( user => user.favColor.toLowerCase() === color.toLowerCase())
if (users.length) {
return users
}
throw new ReferenceError(`No users favorite color is ${color}`)
}
}