LoginSignup
84
72

More than 5 years have passed since last update.

nodejs + express + sequelize webサーバ最小構成

Last updated at Posted at 2016-07-25

大量の処理をさばくために、ノンブロッキングI/Oというモデルを採用したプログラミング言語。
今回は「nodejs」 の最小構成を構築して行きたいと思います。

nodejsとは

サーバサイドjavascript。
googleが開発したV8エンジン上で動作する言語。

expressとは

Node.js 向けの高速で最小限の Web フレームワーク。

sequelizeとは

Noje.js向けのORM。PostgreSQL, MySQL, SQLite , MSSQL等をサポート。

環境とIDE

mac osx 10.9.5
mysql 5.6.31
eclipse neon + nodeclipse

nodejsインストール

homebrewでnodejsをインストールします。
npmというnodejsのパッケージ管理ツールも同時にインストールされます。

$ brew install node

express-generatorインストール

express-generatorはexpressのスケルトン(フレームワークの雛形)を作成するためのモジュールです。

$ npm install express-generator -g

expressスケルトン作成

$ express node_base

フォルダ構成は下記のようになります

node_base(workfolder)
├─app.js
├─package.json
├─public
│ ├─images
│ ├─javascripts
│ └─stylesheets
│   └─style.css
├─routes
│ ├─index.js
│ └─users.js
├─bin
│ └─www
└─views
  ├─error.jade
  ├─layout.jade
  └─index.jade

sequelizeインストール

まずはnode_base内のpackage.jsonを修正します。
package.jsonはnpmでの依存関係等をまとめているjsonファイルです。

dependenciesに追加するモジュール。

"mysql": "~2.11.1",
"sequelize": "~3.23.6",
node_base/package.json
{
  "name": "node_base",
  "version": "0.0.0",
  "private": true,
  "scripts": {
    "start": "node ./bin/www"
  },
  "dependencies": {
    "body-parser": "~1.15.1",
    "cookie-parser": "~1.4.3",
    "debug": "~2.2.0",
    "express": "~4.13.4",
    "jade": "~1.11.0",
    "morgan": "~1.7.0",
    "serve-favicon": "~2.3.0",
    "mysql": "~2.11.1",
    "sequelize": "~3.23.6"
  }
}

npm install

追加したモジュールをインストールします。

$ pwd 
path/to/workspace/node_base
$ npm install

sequelize-cliインストール

sequelize-cliはSequelizeコマンドラインインタフェースです。
色々便利なのでインストールしておきます

$ npm install -g sequelize-cli

DB作成 & db migration実行

まずは、sequelizeの環境を作るため初期化します。

$ sequelize init

node_baseフォルダ内に下記のフォルダが作成されます。

node_base(workfolder)
├─config
│ └─config.json # DB周りの設定情報が記載
├─migrations  # sequelize-cliでmigrationファイルを作成した際に格納されるフォルダ
├─seeders
└─models  # sequelize-cliでmodelを作成した際に格納されるフォルダ

作成したmodelに対応したDBのテーブルをmigrationするためにmysqlにDBを作成します。
流し込まれるDBの情報はconfig/config.json内に記載されています。

config/config.json
{
  "development": {
    "username": "root",
    "password": null,
    "database": "node_base",
    "host": "127.0.0.1",
    "dialect": "mysql"
  },
  "test": {
    "username": "root",
    "password": null,
    "database": "node_base_test",
    "host": "127.0.0.1",
    "dialect": "mysql"
  },
  "production": {
    "username": "root",
    "password": null,
    "database": "node_base",
    "host": "127.0.0.1",
    "dialect": "mysql"
  }
}

config.jsonには各環境毎にDB設定情報が記載されています。

SQLファイル作成 & 流し込み

SQLファイルを作成します。

config/db.sql
CREATE DATABASE node_base;

DBに流し込みます。

$ mysql -u root < config/db.sql 

model & migration作成

sequelize-cliでmodelやdb周りを作成して行きます。

model作成

Userモデルを作成します。
下記のコマンドを実行するとmodelsフォルダ内にuser.jsが作られmigrationsフォルダにmodelのcreate用のmigrationファイルが作成されます。

$ sequelize model:create --name User --attributes name:string

migration作成

上記で既にUser modelのmigrationファイルが作成されていますが、ここでmigrationファイルを作成します。db:migrateを実行する時下記のコマンドでmigrationを作成していないと実行できなかったため、おそらく必要なんだと思います。

$ sequelize migration:create

db migration実行

$ sequelize db:migrate

上記のコマンドが完了するとDB内に先ほど作成したUserのテーブルが作成されます。

userAPI作成

express-generatorでスケルトンを作ると既にuserAPIが作成されているのでそちらをいじってuserのidとnameを渡したらUsersテーブルにデータを作成 or 検索を行うようなAPIを作ります。

routes/users.js
var express = require('express');
var models = require("../models");

var router = express.Router();


/* GET users listing. */
router.get('/', function(req, res, next) {
  var user_id = req.query.user_id;
  var name = req.query.name;
  models.User.findOrCreate(
    {"where": {"id": user_id}, 
     "defaults": {"id": user_id, "name": name}}
  ).spread(function(user, created){
    res.send({"user": user, "created": created});
  });
});

module.exports = router;

サーバ起動 & APIテスト

サーバ起動を起動してAPIの確認をしてみます。

$ npm start

http://127.0.0.1:3000/users/?user_id=1&name=test
こちらにアクセスすると

スクリーンショット 2016-07-24 11.43.01.png

github

上記対応を行ったソースコードをgithubにあげているので、興味がある方はcloneしてみて下さい。
https://github.com/yu-sa/node_base

 まとめ

  • defacto standardなモジュール等が充実しており、簡単なwebサーバはすぐ作れるようです。
  • ノンブロッキングI/Oモデルを採用している事により、処理を非同期で実行しレスポンスを速やかに返す頃が出来るため、設計等をしっかりと行えば高速なwebサーバを作成する事が出来そうで、作っていて面白そうな言語であると感じました。
84
72
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
84
72