Adding CRUDing functionality with Typescript
Now we have the first route accessing data we will replicate the other CRUDing routes to illustrate how typescript differs from 'vanilla' Javascript.
Adding an ID Route
Add the following function to the controller.
Here typescript is used to indicate function takes an id
parameter of type string
and returns a Promise
that resolves to either an IFilm
object, null
, or an object with an error
property.
Be sure to add the getDataById
function to the exports:
Add the ID Route
In the route typescript file add the route as follows:
Typescript is used to indicate the parameters req
is of type Request object and res
of type Response.
You will now be able to test the ID endpoint such as http://localhost:3000/api/645268083f37a8fd938b26a1
Adding the Insert Controller
Following the pattern estalished above return to the controller and add the createData
function:
Here typescript is used to indicate function takes a partial of type <IFilm>
as a parameter and returns a Promise
that resolves to either an IFilm
object, null
, or an object with an error
property.
TypeScript uses the concept of Partial
to create a type that represents an object with all properties of a given type as optional. It allows for specifying incomplete objects or objects where some properties may be missing. This reflects the optional values set in the IFilm
interface.
Be sure to add the createData
function to the exports:
Add the Create Route
In the route typescript file add the POST
route as follows:
Typescript is used to indicate the parameters req
is of type Request object and res
of type Response.
Adding the Update Controller
Next add the update controller:
Here typescript is used to indicate function takes an id of type string
and a partial of type <IFilm>
as parameters and again returns a Promise
.
Be sure to add the updateData
function to the exports:
Add the Update Route
In the route typescript file add the PUT
route as follows:
Typescript is used to indicate the parameters req
is of type Request object and res
of type Response.
Adding the Delete Controller
Finally add the delete controller:
Here typescript is used to indicate function takes an id of type string
as parameters to identify the document to delete, and again returns a Promise
.
Be sure to add the deleteData
function to the exports:
Add the Delete Route
In the route typescript file add the DELETE
route as follows:
Typescript is used to indicate the parameters req
is of type Request object and res
of type Response.
Next: Web Views with EJS