Skip to content

Instantly share code, notes, and snippets.

@ducin
Created September 15, 2018 18:31
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ducin/786b72105e496125ffda9e0e8bbf5ba3 to your computer and use it in GitHub Desktop.
Save ducin/786b72105e496125ffda9e0e8bbf5ba3 to your computer and use it in GitHub Desktop.
const API_URL = 'http://localhost:3011/'
const OfficeModel = {
getCollection(){
return fetch(`${API_URL}offices`)
.then(res => res.json())
},
async __extendOfficeWithEmployees(office){
const employees = await EmployeeModel.getCollection(office.city)
return { ...office, employees }
},
async getCollectionWithEmployees(){
const offices = await this.getCollection()
const promises = offices.map(this.__extendOfficeWithEmployees)
return Promise.all(promises)
},
async getItemWithEmployees(city){
const officeRes = await fetch(`${API_URL}offices?city=${city}`)
const office = await officeRes.json()
return this.__extendOfficeWithEmployees(office[0])
}
}
const EmployeeModel = {
getCollection(office){
const query = office ? `?office_like=${office}` : ''
return fetch(`${API_URL}employees${query}`)
.then(res => res.json())
},
getItem(id){
return fetch(`${API_URL}employees/${id}`)
.then(res => res.json())
}
}
const ProjectModel = {
getCollection(){
return fetch(`${API_URL}projects`)
.then(res => res.json())
},
getItem(id){
return fetch(`${API_URL}projects/${id}`)
.then(res => res.json())
},
async __extendProjectWithEmployees(project){
const managerPromise = EmployeeModel.getItem(project.manager)
const teamPromises = project.team.map(member => EmployeeModel.getItem(member.id))
return { ...project,
manager: await managerPromise,
team: await Promise.all(teamPromises)
}
},
async getItemWithEmployees(id){
return this.__extendProjectWithEmployees(await this.getItem(id))
}
}
////////////////////////////////
OfficeModel.getCollection()
.then(offices => console.log('offices', offices))
EmployeeModel.getCollection()
.then(employees => console.log('employees', employees))
ProjectModel.getCollection()
.then(projects => console.log('projects', projects))
ProjectModel.getItemWithEmployees("579ef28f-c539-41ff-abe2-e4f6b1c1afed")
.then(project => console.log('project with employees', project))
OfficeModel.getItemWithEmployees('Dallas')
.then(office => console.log('office with employees', office))
OfficeModel.getCollectionWithEmployees()
.then(offices => console.log('all offices with employees', offices))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment