Skip to content

Instantly share code, notes, and snippets.

@matfin
Created January 17, 2021 19:25
Show Gist options
  • Save matfin/80df82790e4cb2edd7d6acb7a063a92e to your computer and use it in GitHub Desktop.
Save matfin/80df82790e4cb2edd7d6acb7a063a92e to your computer and use it in GitHub Desktop.
Get a course for a student
const courses = [
{
"courseData" : [
{
"course" : {
"day" : "Tuesday",
"duration" : "10 weeks",
"language" : "German",
"location" : "Online",
"startdate" : "12th January",
"term" : "January",
"time" : "17.30-18.30",
"timeofday" : "Evening",
},
"courseID" : "JRNGETNXXOLTUV",
"dates" : {
"class1" : "12/01/2021",
}
}
]
},
{
"courseData" : [
{
"course" : {
"day" : "Wednesday",
"duration" : "20 weeks",
"language" : "Italian",
"location" : "The Shed",
"startdate" : "12th January",
"term" : "January",
"time" : "17.30-18.30",
"timeofday" : "Midnight",
},
"courseID" : "GETNXXOLTUVABC",
"dates" : {
"class1" : "13/01/2021",
}
}
]
},
];
const users = {
'kwvjUSgZKXXfxxxxxxxxxxxxxxxxxx' : {
courseID : "JRNGETNXXOLTUV",
email : "[email protected]",
username : "Test",
},
'vXf4WcRGQcxxxxxxxxxxxxxxxxxxx' : {
"courseID" : "JRNGETNXXOLTUV",
"email" : "[email protected]",
"username" : "Test Test"
}
};
// simulating a call to an API or DB to fetch a user
const fetchUser = (id) => {
const user = users[id];
return new Promise(resolve => resolve(user));
};
const fetchCourse = (courseID) => {
// courses.find will return the first item it finds given the matching function
const course = courses.find(course => {
// go through all courses and return the one with a matching courseID
return course.courseData[0].courseID === courseID;
});
return new Promise(resolve => resolve(course));
}
const run = async () => {
// lets wait until we get the user
const user = await fetchUser('kwvjUSgZKXXfxxxxxxxxxxxxxxxxxx');
// then get the courseID (assuming one to one relationship)
const courseID = user.courseID;
// then with that, get the one course we want from all the courses
const course = await fetchCourse(courseID);
// now we have the user and the course
console.log(user, course);
};
run();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment