Users Collection - ldco2016/microurb_web_framework GitHub Wiki

import { User } from "./models/User";

const user = User.buildUser({ id: 1 });

user.on("change", () => {
  console.log(user);
});

user.fetch();

The class of user is looking great, the class model is also looking great, but there is one big hole in the entire setup now.

Inside the fetch function:

fetch(id: number): AxiosPromise {
    return axios.get(`${this.rootUrl}/${id}`);
  }

I can only call this thing if I have the id of the record that I want to fetch. This is actually a very big problem because it introduces a kind of chicken and egg scenario inside of my program. The problem is that when the application starts, there is no knowledge of what ids are available. So when the program starts up I have to hard code some ids in as I am doing right here:

const user = User.buildUser({ id: 1 });

If I have some big collection of users stored inside of my JSON Server, I cannot currently somehow get a list of those different ids and know what different users exist. I would have to write out code that makes the user with id of 1,2,3 and so on and fetch each of these and only then know that user with a certain id exists.

That is clearly not a good solution.

So I need to figure out a way to somehow figure out what different users exist on my backend. To do so, I will use the built-in functionality of JSON Server. I am talking about the RESTful conventions here:

One of the different convention methods was to make a GET request to /users and if I do that I should retrieve a list of all the users from the backend server. I can essentially use that route of /users as a way to figure out what different users exist on the backend. So if I want to show a list of all different users, I make a request to that /users endpoint, get all of my users and render them to the screen.

In order to build this out I need to make a collection class of sorts.

Screen Shot 2021-08-04 at 12 39 44 PM

I will call it class UserCollection. Maybe it will have a models property which will be an array of User. Maybe it will also have access to Eventing and the fetch() method. So if I call fetch(), UserCollection will make a request to /users, get all the users, get a ton of that JSON data and take that data and turn them into instances of users available on the models property.

I will eventually refactor it to make it more reusable and call it class Collection and for the model, instead of User[], it will be T[], which is a generic, because I will want to use this class Collection to represent many types of collections and not just users.