Transaction operations in assign-routes.js

The assign-routes.js file defines routes and adds them to the express instance (app) created in index.js. In Express, routes can be defined directly on app (for example, app.get()), or through the use of a Router. In this case, a Router was used to add multiple methods to the same route path. The following code, taken from the assign-routes.js file, creates a Router instance and adds two routes: a GET route that returns all transactions, and a POST route that creates a new transaction:

module.exports = function assignRoutes(app, assets) {
const { db, wasmInstance } = assets;
const transaction = new Transaction(db, wasmInstance);
const transactionsRouter = express.Router();

transactionsRouter
.route('/')
.get((req, res) => {
const transactions = transaction.findAll();
res.status(200).send(transactions);
})
.post((req, res) => {
const { body } = req;
if (!body) {
return res.status(400).send('Body of request is empty');
}
const newRecord = transaction.add(body);
res.status(200).send(newRecord);
});

...

// Set the base path for all routes on transactionsRouter:
app.use('/api/transactions', transactionsRouter);
}

The app.use() function at the end of the snippet specifies that all routes defined on the transactionsRouter instance are prefixed with /api/transactions. If you were running the application locally on port 3000, you could navigate to http://localhost:3000/api/transactions in your browser and see an array of all the transactions in JSON format.

As you can see from the body of the get() and post() functions, interactions with any transaction records are being delegated to the Transaction instance created in line 3. That completes our review of pertinent sections of the code base. Each of the files contain comments describing the file's functionality and purpose, so you may want to review those before moving on to the next section. In the next section, we'll build, run, and interact with the application.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset