Web framework with typescript – Update from and Save to Server

The techniques we use here is called Composition. We compose different objects and have them work together.

To start off, we have a json server with its initial content like so:

db.json

Updating a User from the server

So we have a user. In order to update it from the latest data from the server, we’ll register an event ‘change’ and to pass a callback to let us know when it is done.

1) REGISTER event on

Once our event has been saved, we call fetch which does two things:

  1. It fetches the data from server
  2. Once data arrives, we update it locally using Attributes (Object.assign)
  3. Then our Eventing will trigger ‘change’ to execute the callback

2) FETCH data from server

where fetch is:

3) Set local properties

and set function is:

4) Trigger event Change for completion

Saving user Data

First, we have the sync class

The save function says, we are passed in data that must have an optional id property.
If this id exists then we do a PUT request, which updates the user on the server.
If this id doesn’t exist, then we simply make a POST request, which creates the user on the server.

In our attributes class, implement a getAll function that returns all attributes as an object. This is naturally our dictionary this.data:

Now we are ready to implement save() for User.
Use use User’s sync property and call save.
That function looks to see if id exists in the Attributes object.

If id does exist, we update the user on the server by making a PUT request.

If id doesn’t exist, it creates a user on the server by making a GET request.

The save function return a Promise. We call then on it so when the async function completes, it will come to our callback. In the callback, we simply trigger the ‘save’ event to let it know that our operation has completed

In index.tsx

To update User

To create New User