Skip to content

md-adil/node-starter

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

10 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Simple Node js starter with express routing and objection model.

git clone https://github.com/md-adil/node-starter my-project
cd my-project
yarn
cp .env.example .env
# change .env file update database name & settings
yarn migrate
yarn start

We have already written some codes for you

HOME

GET /
// homeController
exports.index = req => {
    return "Hello World"
}
GET /different-code
// homeController
const Response = require("../http/response");

exports.diffCode = req => {
    return new Response("Hello World", 300);
}

Login

// src/routes/api.js

const controller = require("../controllers"),
    loginController = controller("auth/loginController");
route.post("/login", loginController.login);
// src/controllers/auth/loginController.js

exports.login = async req => {
    if (!req.body.email || !req.body.password) {
        throw new ValidationError('Email and password is required')
    }
    const user = await User.query().where('email', req.body.email).first();
    if (!user) {
        throw new ValidationError('Invalid credentials');
    }
    if (!await bcrypt.compare(req.body.password, user.password)) {
        throw new ValidationError('Invalid credentials');
    }
    const token = jwt.sign({ iat: (new Date()).getTime(), sub: user.id }, config.key);
    return {
        token, user
    }
}

Request

POST /api/login

Headers

Content-Type: application/json
Accept: application/json

Required Accept: application/json when need json as response

Request body

{
    "email": "someemail@somedomain.com",
    "password": "password"
}

Response

Error response body with status code 422

{
    "message": "Invalid credentials"
}

Success Response body

{
    "token": "<token>",
    "user": {
        "id": 1,
        "name": "Name",
        "email": "someemail@somedomain.com",
    }
}

Resister

// src/routes/api.js

const registerController = controller("auth/registerController");
router.post("/users", registerController.register);
// src/controllers/auth/registerController.js

exports.register = async req => {
    if (await User.query().where('email', req.body.email).select('id').first()) {
        throw new ValidationError("It seems someone has already take this email address.");
    }
    const user = await User.query().insert({
        name: req.body.name,
        email: req.body.email,
        password: await bcrypt.hash(req.body.password, 10)
    });
    const token = jwt.sign({iat: (new Date).getTime(), sub: user.id}, config.key);
    return {
        token, user
    }
};

Fetching users

// src/routes/api.js

const controller = require("../controllers");
const userController = controller("userController");

router.get("/users", userController.index);
// src/controllers/userController.js

const { ResponseError } = require("../errors");
const User = require("../models/User");

exports.index = async req => {
    if (!req.query.page) {
        throw new ResponseError(
            "Page is required" /** response error message */,
            422 /** Response error code */
        );
    }
    return User.query().page(req.query.page, 25);
};

Request

GET /api/users?page=1

Headers

Accept: application/json
Authorization: <token> // the token from login response

Required Accept: application/json when need json as response

Response

Error response body with status code 422

{
    "message": "Page is required"
}

Success Response body

{
    "results": [
        {
            "id": 1,
            "name": "Adil",
            "email": "adil.sudo@gmail.com",
        },
        {
            "id": 2,
            "name": "Adil",
            "email": "md-adil@gmail.com",
        }
    ],
    "total": 2
}

Database and Migrations

Migrate database

yarn migrate

Connect database through native client

yarn db:connect

Show all tables through native client

yarn db:tables

Explain table through native client

yarn db explain users

Select from tables with or without limit through native client

yarn db select users 100 # default 1000

Note

This is only for mysql and rest api.

This is basic setup, how I use in my production environment, I want to extend it as full-fledged another javascript backend framework. Need some feedback and suggestion.

Thanks In Advanced, Adil.

About

No description, website, or topics provided.

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors