XEST-103 CRUD Operations
In order to read/create/update/delete an artist you need 3 things;
- Controller
- Actions
- Query functions
Endpoints
Have a look at the folder structure you should be creating;
In the app folder, you can see routers.js file where you will be writing your endpoints.
Query Function, Action, Controller
- Start by writing the query for inserting an artist in your
src/actions/artists/createArtist/queries/insertArtist.js
const { submitQuery, getInsertId } = require("~root/lib/database");
const insertArtist = ({ name, genre }) => submitQuery`
INSERT INTO Artists(name, genre)
VALUE(${name}, ${genre});
`;
module.exports = getInsertId(insertArtist);
- Followed by that you need to write your action in your
src/actions/artists/createArtist/index.js
const insertArtist = require("./queries/insertArtist");
const createArtist = async ({ name, genre }) => {
const artistId = await insertArtist({ name, genre });
return { artistId };
};
module.exports = createArtist;
- Start by writing a post function in your
src/app/controllers/Artists/postArtist/index.js
file which should look like the following
const handleAPIError = require("~root/utils/handleAPIError");
const createArtist = require("~root/actions/artists/createArtist");
const postArtist = async (req, res) => {
const { name, genre } = req.body;
try {
const { artistId } = await createArtist({ name, genre });
res.status(201).send({
artistId
});
} catch (err) {
handleAPIError(res, err);
}
};
module.exports = postArtist;
In this file, if the createArtist function works, you get 201 status code and get your artistId however if you have an error, you will get an API error accordingly. (these api errors will come from your constants folder; HttpStatusCodes.js file, feel free to go and check the relevant file.)
- Then add the following;
router.post("/artists", postArtist);
route to your src/app/routes.js
after defining and requiring the function at the top of the file.
In these 3 files you can see that you have created a query first - used that query in your actions and use that action in your controller by importing each other.