OpenShiftでMEAN Stackを試してみた

[OpenShift]:http://www.openshift.com
[Postman]:https://chrome.google.com/webstore/detail/postman-rest-client-packa/fhbjgbiflinjbdggehcddcbncdddomop
[OpenShift][OpenShift]でMEAN Stackを試してみたときのメモです。

MEANといいなが、AngularJSは、まだです....
MongoDBとの接続は、mongooseを使っています。
OpenShiftへのサインインや開発環境整備については、割愛します。

##フォルダ構成

フォルダ構成は、以下のとおりです。
OpenShiftから、git clone した後、

+ npm にて、必要パッケージのインストール
+ package.json の修正
+ server.js の修正
+ app/models/bear.js の追加

を行っています。
![01.PNG](https://qiita-image-store.s3.amazonaws.com/0/44002/7916a89a-875a-faea-1142-c45d9cbcc70d.png)
<br />
##package.jsonの設定

package.json は、こんな感じです。

```json:package.json
{
  "name": "itheart-openshift-sample",
  "version": "1.0.0",
  "description": "OpenShift Sample Application MEAN stack",
  "keywords": [
    "OpenShift",
    "Node.js",
    "application",
    "openshift"
  ],
  "author": {
    "name": "itheart",
    "email": "youritheart@gmail.com",
    "url": "http://www.itheart.com/"
  },
  "engines": {
    "node": ">= 0.6.0",
    "npm": ">= 1.0.0"
  },
  "dependencies": {
    "express": "4.0.0",
    "mongoose": "3.6.20",
    "body-parser":  "1.0.2"
  },
  "devDependencies": {},
  "bundleDependencies": [],
  "private": true,
  "main": "server.js",
  "jshintConfig": {
    "node": true
  }
}

```

<br />
##server.jsの内容
server.jsは、こんな感じです。

```js:server.js
// server.js

// BASE SETUP
// =============================================================================

// call the packages we need
/*jslint node: true */
var express    = require('express');        // call express
var app        = express();                 // define our app using express
var bodyParser = require('body-parser');
var mongoose   = require('mongoose');
var Bear       = require('./app/models/bear');

var connection_string = '127.0.0.1:27017/' + process.env.OPENSHIFT_APP_NAME;

if (process.env.OPENSHIFT_MONGODB_DB_URL) {
	connection_string = process.env.OPENSHIFT_MONGODB_DB_URL +
	process.env.OPENSHIFT_APP_NAME;
}

mongoose.connect(connection_string);


// configure app to use bodyParser()
// this will let us get the data from a POST
app.use(bodyParser());

var ipaddress = process.env.OPENSHIFT_NODEJS_IP;
var port = process.env.OPENSHIFT_NODEJS_PORT || 8080;        // set our port

// ROUTES FOR OUR API
// =============================================================================
var router = express.Router();              // get an instance of the express Router

// test route to make sure everything is working (accessed at GET http://localhost:8080/api)
router.get('/', function(req, res) {
    res.json({ message: 'hooray! welcome to our api!' });   
});

router.route('/bears')
	.post(function(req, res) {

		var bear = new Bear();
		bear.name = req.body.name;

		bear.save(function(err){
			if (err)
				res.send(err);

			res.json({ message: 'Bear Create!' });
		});
	})

	.get(function(req, res) {
		Bear.find(function(err, bears) {
			if (err)
				res.send(err);

			res.json(bears);
		});
	});

router.route('/bears/:bear_id')
	.get(function(req, res) {
		Bear.findById(req.params.bear_id, function(err, bear) {
			if (err)
				res.send(err);

			if (bear)
				res.json(bear);
			else
				res.json({ message: req.params.bear_id + ' is not found!' });
		});
	})

	.put(function(req, res) {
		Bear.findById(req.params.bear_id, function(err, bear) {
			if (err)
				res.send(err);

			if (bear) {
				bear.name = req.body.name;

				bear.save(function(err){
					if (err)
						res.send(err);

					res.json({ message: 'Bear Update!' });
				});
			} else {
				res.json({ message: req.params.bear_id + ' is not found!' });
			}
		});
	})

	.delete(function(req, res) {
		Bear.remove({
			_id: req.params.bear_id
		}, function(err, bear) {
			if (err)
				req.send(err);

			if (bear)
				res.json({ message: 'Bear Delete!' });
			else
				res.json({ message: req.params.bear_id + ' is not found!' });
		});

	});

// more routes for our API will happen here

// REGISTER OUR ROUTES -------------------------------
// all of our routes will be prefixed with /api
app.use('/api', router);
app.use(express.static(__dirname + '/public'));

// START THE SERVER
// =============================================================================
app.listen(port, ipaddress);
console.log('Magic happens on port ' + port);
```

<br />
##bear.jsの内容
bear.jsは、こんな感じです。

```js:app/models/bear.js
var mongoose = require('mongoose');
var Schema   = mongoose.Schema;

var BearSchema = new Schema({
	name: String
});

module.exports = mongoose.model('Bear', BearSchema);
```

<br />
## postmanによる確認
[Postman][Postman]にて確認した結果は、以下のとおりです。

![/api/bears - GET](https://qiita-image-store.s3.amazonaws.com/0/44002/c4b864d1-2f64-2a65-9989-fc95af7eb087.png)

<br />
## 次は...
AngularJSを構築予定です...