Merced-Express: If Express Met Ruby on Rails

  • The ability to quickly generate models, migrations and controllers
  • Pretty easy plug’n’play database integration
  • DB commands simplifying things like resetting and seeding the database

Creating a Todo App with Authentication

Generating the Project

  • cd into the todoapp folder
  • run npm install

Configuring Settings

  • create a .env file in the project root and define the following
DATABASE_URL=mongodb://username:password@host/databasename
SECRET=secretforjwttokens
PORT=3000

Generating The Todo Model

//----------------------------------------
// New Schema
//----------------------------------------
const TodoSchema = new Schema({
subject: String
}, { timestamps: true });
  • If you notice all the routes are already all set in the TodoController in the controllers folder and it has already been registered as a router with the HomeController.

Adding Authentication

//----------------------------------------
// Import Dependencies
//----------------------------------------
import { Router } from "express";
import Todo from "../models/Todo.js";
import auth from "../config/auth.js"
//----------------------------------------
// Create Router
//----------------------------------------
const TodoRouter = Router();
//----------------------------------------
// Router Middleware
//----------------------------------------
TodoRouter.use(auth)

Testing

  • create a new user with a post request to /user/create (username and password in request body)
  • login and receive a token with a post request to /user/login (username and password in request body)
"Authorization":"bearer <token>"
index => get request to /todo
show => get request to /todo/:id
create => post request to /todo
update => put request to /todo/:id
destroy => delete request to /todo/:id

That’s it!

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store