Main Features of Koa.js
Koa is a new web framework designed by the team behind Express, which aims to be a smaller, more expressive, and more robust foundation for web applications and APIs. By leveraging async functions, Koa allows you to ditch callbacks and greatly increase error-handling. Koa does not bundle any middleware within its core, and it provides an elegant suite of methods that make writing servers fast and enjoyable.
- Lightweight and modular.
- No callback hell.
- Better error handling through try/catch.
- Better user experience.
- Proper stream handling.
Installation
You can quickly install a supported version of node with your favorite version manager:
$ nvm install 7
$ npm i koa
$ node my-koa-app.js
reference:https://koajs.com/
How to create simple project
Init a npm project:
npm init
Install Koa “koa”. Save it as a dev dependency
$ npm install koa
Create a file named server.js and require “koa” dependency to it.
const Koa=require('koa')
Create a Koa web server that returns ‘Hello World’ to all requests.
const app = new Koa();
app.use(ctx => {
ctx.body = 'Hello World';
});
app.listen(3000);console.log('Application is running on port 3000');
Run your application. Perform HTTP requests to http://locahost:3000
You should see “Hello World” plain test coming.
Install “@koa/router” to your project.
npm install koa-Router
Create a new file named home.router.js inside the directory named routes. Import “@koa/router”.
Inside the new file, register following routes.
const Router=require('@koa/router')
const router = new Router({
prefix: '/home'
});
router.get('/', ctx => {
ctx.body = 'Hello World11';
});
router.post('/', ctx => {
ctx.body = 'Hello World22';
});
Export the “router” object you created in the above.
module.exports=router;
Import this file to your server.js file.
const homeRouter = require('./routes/home.router');
You need your server to understand JSON type that can be achieved by using body parser.
a. Install koa-bodyparser
//bodyParser convert data to json
const bodyParser = require('koa-bodyparser');
b. Register this with your koa app
//create koa app
const app = new Koa();
//bodyParser() is middleware it convert body to json
app.use(bodyParser());
//create router (Introduce new router to route app)
Register these routes with your Koa application. You need to allow HTTP methods while registering. This should be executed before listening to port 3000. You need to remove or put the below code before the previously created app.use in 4 (which returned Hello World to any request) or remove that part entirely. This is because that global listener will reply before your specific router capture the request.
app.use(homeRouter.routes())
//registering all ther routers from home router and register
//all allowed methods from home router(get,post methods)
.use(homeRouter.allowedMethods());
Try out your newly created two routes prefix with http://localhost:3000/home
Next create a new file called “posts.api.js”. This will be your application logic. This should be under the directory “api”.
Install and import the dependency “uuid” to your newly created file.
const UUID=require('uuid');
Your “posts.api.js” should support below. Use your basic Node and JS knowledge to achieve this.
a. Create a global Map called “posts” to hold posts created by users.
const posts=new Map();
b. Create a method “createPost” that accepts an object with properties (name, description)
c. This method should add new post passed to it to the Map by adding two new properties “id” and “postedDate”.
i. ID should be created using imported UUID library method “uuid.v4()”.
ii. Posted Date should be set using the JS Date class “new Date()”.
iii. Map has a method called set that can be used to add a new key and value to it. User the created ID field as the key., value should be the complete post object.
d. Add another method “getPosts” that returns all posts created.
i. You should use the methos called “values()” in map.
- Try the spread syntax to expand map values as an array “[…map.values()]”. e. Other method “getPost” should accept the argument “id”. This should return the post with that ID.
- Use the map method “get(key)” method to fetch the object by your key (ID). f. Make sure you export all these methods.
const CreatePost =({name,description})=>
{
const post = {
id:UUID.v4(),
name,
description,
postedDate:new Date()
}
posts.set(post.id,post);
return post;
}
const getPosts =() =>
{
return[...posts.values()];
}
const getPost = id =>
{
return posts.get(id);
}
module.exports={
CreatePost,
getPosts,
getPost
};
create a new file “post.routes.js”. Same as before import router and the 3 method you create in the previous exercise.
const Router=require('@koa/router'),
{CreatePost,getPosts,getPost}=require('../api/posts.api');
const router = new Router({
prefix: '/posts'
});
router.get('/', ctx => {
ctx.body = getPosts();
});
router.post('/', ctx => {
let post=ctx.request.body;
post=CreatePost(post);
ctx.response.status=201;
ctx.body=post;
//ctx.body = 'Hello World22';
});
router.get('/:id', ctx => {
const id=ctx.params.id;
ctx.body=getPost(id);
//ctx.body = 'Hello World11';
});
module.exports=router;