...
| Resources | | --------- | | Express routing | | Objection query builder | | Knex query builder | | Objection withGraphFetched | | Objection transactions | | Objection hooks |
1.Get endpointsGet endpoints
Get endpoints return
objects from a single table
{...crop}
nested objects
{...location, figure: {...figure, area }, field}
objects from joined tables
{...userFarm, ...user, ...farm}
(mostly legacy code)
...
Code Block |
---|
//should avoid const userFarmModel = require('../models/userFarmModel'); const userFarmController = { getFarmInfo() { return async (req, res) => { try { const user_id = req.params.user_id; const farm_id = req.params.farm_id; const rows = await userFarmModel.query().context({ user_id: req.auth.user_id }).select('*') .where('userFarm.user_id', user_id).andWhere('userFarm.farm_id', farm_id) .leftJoin('role', 'userFarm.role_id', 'role.role_id') .leftJoin('users', 'userFarm.user_id', 'users.user_id') .leftJoin('farm', 'userFarm.farm_id', 'farm.farm_id'); return res.status(200).send(rows[0]); } catch (error) { return res.status(400).send(error); } }; }, }; |
Copy
2.Post endpointsGet endpoints
Add a single entity
Code Block |
---|
const NewEntityModel = require('../models/newEntityModel'); const newEntityController = { addNewEntity() { return async (req, res, next) => { try{ const result = await NewEntityModel.query().context(req.auth).insert(req.body); return res.status(201).send(result); }catch(error){ return res.status(400).json({ error }); } } }, } module.exports = newEntityController; |
...
Always use transactions when an endpoint performs more than 1 insert/update/delete
Steps for a backend - frontend story from a data flow perspective
Create knex migration to create/modify tables in database
Create objection models
Endpoints and empty controllers
Backend jest unit testing
Implement controllers
Create authorization/validation middlewares
Run tests and make sure everything passes
Create pure frontend components in storybook
res.data normalizer, redux slice, redux selectors to hold and access the data
Redux saga for get/post/put/patch request
Container component to connect saga actions/selector with pure components
Connect Route component with container components with react router
Manual testing