Permalink
Cannot retrieve contributors at this time
Name already in use
A tag already exists with the provided branch name. Many Git commands accept both tag and branch names, so creating this branch may cause unexpected behavior. Are you sure you want to create this branch?
TEACHING-MATERIALS/exercises/09_api_basics/bookshop/async/modules/favourites.js
Go to fileThis commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
69 lines (55 sloc)
1.63 KB
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
'use strict' | |
const db = require('./db') | |
const errors = require('./errors') | |
async function favourites(user) { | |
/* Get a connection to the user's favourites */ | |
return await db.connect(`favourites/${user}`) | |
} | |
async function list(user) { | |
const favs = await favourites(user) | |
return await favs.list() | |
} | |
async function add(user, book) { | |
const favs = await favourites(user) | |
return await favs.add(book.id, book) | |
} | |
async function get(user, id) { | |
const favs = await favourites(user) | |
return await favs.get(id) | |
} | |
async function update(user, book) { | |
const favs = await favourites(user) | |
return await favs.update(book.id, book) | |
} | |
async function delete_(user, id) { | |
const favs = await favourites(user) | |
return await favs.delete(id) | |
} | |
/* DANGER */ | |
async function clear(user) { | |
const favs = await favourites(user) | |
return await favs.clear() | |
} | |
function validate(fav) { | |
const data = fav => !!fav | |
const id = fav => !!fav.id | |
const title = fav => !!fav.title && typeof fav.title === 'string' | |
const description = fav => !!fav.description && typeof fav.description === 'string' | |
const review = fav => !fav.review || typeof fav.review === 'string' | |
const stars = fav => !fav.stars || ( typeof fav.stars === 'number' && fav.stars >= 0 && fav.stars <= 5 ) | |
const checks = [data, id, title, description, review, stars] | |
const passes = check => check(fav) | |
if (checks.every(passes)) { | |
return true | |
} else { | |
throw new errors.ValidationError() | |
} | |
} | |
module.exports = { | |
validate: validate, | |
list: list, | |
add: add, | |
get: get, | |
update: update, | |
delete: delete_ | |
} |