Server-side CRUD implementation using Koa

Nirasha Jayasiri
4 min readMay 2, 2022

Koa.js is a minimal and flexible Node.js web application framework that provides robust features for web and mobile applications. It is an open-source framework developed and maintained by the creators of Express.js, the most popular node web framework.

Koa has a small footprint (600 LoC) and is a very thin layer of abstraction over the node to create server-side apps. It is completely pluggable and has a huge community. This also allows us to easily extend Koa and use it according to our needs. It is built using the bleeding edge technology (ES6) which gives it an edge over older frameworks such as express.

In this article, we’ll look at how to implement backend CRUDs using Koa.

Getting started

You can use your preferred IDE for the development of this application. First, create a folder and open it with your IDE and open a terminal.

Then give this command to initialize your project.

npm init

The npm init command in the JSON language creates a package.json file for your project’s frontend. A package.json file is a file that contains information about the project’s packages and dependencies. It also contains metadata for the project such as version number, author, and description.

Then we need to install the Koa package by running;

npm i koa

Other than that, install these dependencies as well

npm i @koa/router

Router middleware for Koa. It Provides RESTful resource routing.

npm i koa-bodyparser

A body-parser for Koa, based on co-body. support JSON, form, and text type body.

Now we can implement our application.

Create a file named server.js and modify the package.json file as below.

“main”: “server.js”

Add a script called start as well.

“start”: “node server.js”

Then we will write our first code in the server.js file.

import Koa from ‘koa’;
const app = new Koa();
app.use(async ctx => {
ctx.set(‘Content-Type’, ‘text/html’);
ctx.body = ‘<h3>Koa CRUD App</h3>’;
ctx.status = 200;
});
app.listen(3000, (data) =>{
console.log(“server is running on port 3000”);
})

In the code above, we instantiate the Koa app with the Koa constructor. Then we called app.use with an async function that takes the ctx object.

The async function is called middleware. It’s the basic building block of a Koa app. It runs in a stack-like manner upon request. It’s similar to other frameworks like Express which runs a chain of middleware in order to process incoming requests.

Then you can run the application using the terminal by giving the command:

npm start

open a browser and go to http://localhost:3000 and it will display as Koa CRUD App.

Then we will create REST APIs using Koa. In this article, we are going to implement the crud functions for a student entity. We will use a Map to store data.

Create a folder called api inside the root folder. Create a JavaScript file named students inside the api directory.

Inside the students.js file put the below code.

import {randomBytes} from ‘crypto’;const students = new Map();export const createStudent = ({firstName,lastName,grade }) =>{const student = {id: randomBytes(16).toString(“hex”),firstName,lastName,grade };students.set(student.id,student);return student;}export const getStudent = (id)=>{const student = students.get(id);if(!student){throw new Error(`student not found in id ${id}`);}return student;}export const getAllStudents = ()=>{return […students.values()];}export const updateStudent = (id, { firstName,lastName,grade })=>{if(!students.has(id)){throw new Error(`student not found in id ${id}`);}const student = {id, firstName,lastName,grade };students.set(student.id,student);return student;}export const deleteStudent = (id)=>{if(!students.has(id)){throw new Error(`student not found in id ${id}`);}students.delete(id);}

Now let’s create routes. Create a directory called routes and inside that create a file named studentRoutes.js

Inside that file put the below code.

import Router from “@koa/router”;import { createStudent, deleteStudent, getAllStudent, getStudent, updateStudent } from “../api/student “;const studentRouter= new Router({prefix: ‘/students’});studentRouter.post(‘/’, (ctx)=>{const data = ctx.request.body;ctx.body = createStudent(data);ctx.set(‘Content-Type’, ‘application.json’);ctx.status = 201;});studentRouter.get(‘/:id’, (ctx) =>{const id = ctx.params.id;ctx.body = getStudent(id);ctx.set(‘Content-Type’, ‘application.json’);ctx.status = 200;})studentRouter.get(‘/’,(ctx)=>{ctx.body = getAllStudents();ctx.set(‘Content-Type’, ‘application.json’);ctx.status = 200;})studentRouter.put(‘/:id’,(ctx)=>{const id = ctx.params.id;ctx.body = updateStudent(id,ctx.request.body);ctx.set(‘Content-Type’, ‘application.json’);ctx.status = 200;})studentRouter.del(‘/:id’,(ctx)=>{const id = ctx.params.id;deleteStudent(id);ctx.status = 204;})export default studentRouter;

now let’s add the following code to the server.js file.

import Koa from ‘koa’;import bodyParser from ‘koa-bodyparser’;import studentRouter from ‘./routes/studentRoutes’;const app = new Koa();app.use(bodyParser());app.use(studentRouter.routes());app.use(studentRouter.allowedMethods());

now you can run the project using the command;

npm start

you can check the apis using postman.

Click here to Download postman

Conclusion

In this article, I have presented how to develop server-side CRUD functions using Koa js.

--

--