Skip to content

API Abstraction

Yossi Kolesnicov edited this page Jul 25, 2018 · 1 revision

To interact with the backend, the front-end requires prior knowledge of the APIs provided by the backend. For example, in order to retrieve all the todo items in a To Do app, the developer of the front-end would have to know that the API to call is /api/todo. For marking a todo item as 'Done', the API could be POST /api/todo/{ID}/close or it could be PUT /api/todo/{ID} with the new status, or it could be PATCH /api/todo/{ID} with only the new status.

In the front-end code, we usually create a service layer that mirrors the backend API, so the API can be defined once in the front-end and thereafter developers can use that service instead of fetching data directly through HTTP. Paris provides an easy way to define these services, which it calls 'Repositories', by just defining the data models and API endpoints involved.

Example:

First, we define an entity:

@Entity({
    singularName: "Todo item",
    pluralName: "Todo items",
    endpoint: "todo"
})
export class TodoItem extends EntityModelBase<number>{
    @EntityField()
    text:string;

    @EntityField()
    date:Date;

    @EntityField()
    status:TodoItemStatus;
}

This does the following:

  1. Defines a TypeScript class that represents our app's TodoItem
  2. Defines the API from which data is retrieved from backend for todo items (endpoint: "todo")
  3. Registers the TodoItem class as a Paris Entity (the @Entity decorator does this).

Now that we have a Paris Entity, we can use Paris for fetching data and getting it as strong-typed objects:

const paris = new Paris({ apiRoot: '/api' });

// HTTP call: GET /api/todo
paris.query(TodoItem)
    .subscribe((todoItems:DataSet<TodoItem>) => console.log('Current items: ', todoItems.items));

// HTTP call GET /api/todo/1
paris.getItemById(TodoItem, 1)
    .subscribe((todoItem:TodoItem) => console.log('Todo item with ID === 1: ', todoItem));

The idea is that as long as you define the data with its API, Paris creates everything required to fetch (or save, or delete) that data and return it as class instances, rather than raw JSON.

See more options for configuring an Entity

Clone this wiki locally