项目作者: 7kmCo

项目描述 :
A simple Koa.js boilerplate which implements sequelize and mysql-postgresql
高级语言: JavaScript
项目地址: git://github.com/7kmCo/koa-example.git
创建时间: 2018-09-28T13:15:56Z
项目社区:https://github.com/7kmCo/koa-example

开源协议:

下载


Koa example/boilerplate

This repository demonstrates the usage of Sequelize within an Koa application.

Starting App

First of all, don’t forget to edit /config/config.js, create database then run:

  1. npm install
  2. npm start

This will start the application and create database tables.
Just open http://localhost:3000.

Sequelize Setup

Now we will install all sequelize related modules.

  1. # install ORM , CLI and SQLite dialect
  2. npm install --save sequelize sequelize-cli mysql2
  3. # generate models
  4. node_modules/.bin/sequelize init
  5. node_modules/.bin/sequelize model:generate --name User --attributes firstName:string,lastName:string,email:string

Authentication

There is several authentication strategies available. You can use which one you want and remove those you don’t want.

Available strategies:

  • local
  • google
  • twitter
  • facebook

For routes you want to be accessable only by authenticated users, authenticated middleware can be used like:

  1. router.get('/authenticated-route', authenticated(), async (ctx, next) => {
  2. ctx.body = 'You are logged in'
  3. })

Authenticated middleware is in /utils/index.js

Database Relationships

For demonstrating ORM relationship, Post model created. The relationship is between users and posts like”

  1. Post.belongsTo(User, {as: 'Author'})

You can find examples of relationship when creating new post, which each post will be associated to a user and also in route /posts/user-posts/ which gets all posts of logged in user.