Adding New Routes
In this lesson, we'll be adding a few new routes and return mock data as responses.
We'll cover the following...
Get all your books
Let’s go ahead and make our mock data. We’ll use an array of JSON objects to define a list of books.
export interface IBook { id: string; name: string; author: string; genre: string; }
Go ahead and open up books.ts
. You should notice many new changes. Let’s start at the top.
-
See the import statement mention
types.ts
inline 1
? Open the file. -
We’ve defined an interface,
IBook
, inline 1
, with the basic shape of the data pertaining to a single book. It has the attributes ofname, author, id
, andgenre
. In essence, we have defined a custom type, which we can use to define our data. -
Switch back to
books.ts
and you’ll notice an array of JSON objectbooks
online 3
, which is of typeIBook[]
- i.e., an array of our custom type. Each book has an id, name , author, and genre. -
Scrolling down, you’ll find our old
getBooks
method inline 42
. Now, instead of “Hello World”, we’re returning to a JSON object with two attributes:success
, which will be true, anddata
, which has the value of ourbooks
array. -
Now, if you run your app and make a
GET
request to the URL with/api/v1/books
appended to it, you’ll get the following:
{"success": true,"data": [{"id": "1","name": "The Great Gatsby","author": "F.Scott Fitzgerald","genre": "fiction"},{"id": "2","name": "Little Women","author": "Louisa May Alcott","genre": "fiction"},{"id": "3","name": "Pride and Prejudice","author": "Jane Austen","genre": "romance"},{"id": "4","name": "1984","author": "George Orwell","genre": "sci-fi"},{"id": "5","name": "Moby Dick","author": "Herman Melville","genre": "epic"},{"id": "6","name": "Animal Farm","author": "George Orwell","genre": "allegory"}],}
There you go! Now ...