-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathbind-service.html.md.erb
197 lines (149 loc) · 6.17 KB
/
bind-service.html.md.erb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
---
title: Bind a Service to Your App
owner: Tobias Fuhrimann
---
<strong><%= modified_date %></strong>
The <a href="../service-offerings/index.html" target="_blank">service marketplace</a> has a large number of data stores, from Redis and MongoDB, to MariaDB (fork of MySQL) and RabbitMQ. You can run `cf marketplace` to get an overview. In this step you will add a small MongoDB database to your app.
Create the database:
<pre class="terminal">
$ cf create-service mongodb-2 small my-mongodb
Creating service instance my-mongodb in org MyOrg / space MySpace as user@mydomain.com...
OK
Create in progress. Use 'cf services' or 'cf service my-mongodb' to check operation status.
</pre>
This creates a small MongoDB database for you which we now have to bind to our application. Binding means that the credentials and URL of the service will be written dynamically into the environment variables of the app as `VCAP_SERVICES` and can hence be used directly from there.
Let's bind the new service to our existing application:
<pre class="terminal">
$ cf bind-service my-nodejs-app my-mongodb
Binding service my-mongodb to app my-nodejs-app in org MyOrg / space MySpace as user@mydomain.com...
OK
TIP: Use 'cf restage my-nodejs-app' to ensure your env variable changes take effect
</pre>
<p class="note">
<strong>Note</strong>: If you are getting <code>Server error, status code: 409</code>, please try again after a couple of minutes. It takes a while to spin up that MongoDB for you.
</p>
After that we restage the application as suggested so that it includes the new credentials in its environment variables:
<pre class="terminal">
$ cf restage my-nodejs-app
Restaging app my-app in org MyOrg / space MySpace as user@mydomain.com...
-----> Downloaded app package (8.0K)
-------> Buildpack version 1.5.8
-----> Creating runtime environment
...
</pre>
Now we want to consume our new MongoDB from within our application. Use npm to add the `mongoose` npm module to your dependencies:
<pre class="terminal">
$ npm install --save mongoose
cf-sample-app-nodejs@0.0.0 /.../cf-sample-app-nodejs
└─┬ mongoose@4.4.10
├── async@1.5.2
├── bson@0.4.21
├── hooks-fixed@1.1.0
...
</pre>
Now edit your `app.js` file to use this module to connect to the database specified in your `VCAP_SERVICES` environment variable. We do this by requiring the `mongoose` module and adding a route for the `/kittens` endpoint which returns the `kittens` collection of our MongoDB:
```javascript
'use strict';
// require dependencies
const express = require('express');
const path = require('path');
const favicon = require('serve-favicon');
const logger = require('morgan');
const cookieParser = require('cookie-parser');
const bodyParser = require('body-parser');
const mongoose = require('mongoose');
const routes = require('./routes/index');
// bootstrap our app
const app = express();
let mongoUrl = '';
// check if the app is running in the cloud and set the MongoDB settings accordingly
if (process.env.VCAP_SERVICES) {
const vcapServices = JSON.parse(process.env.VCAP_SERVICES);
mongoUrl = vcapServices.mongodb[0].credentials.uri;
} else {
mongoUrl = 'mongodb://localhost/db';
}
// connect to our MongoDB
mongoose.connect(mongoUrl);
// create a Mongoose schema for kittens
const kittenSchema = mongoose.Schema({
name: 'string'
});
// create a Mongoose model out of our kitten schema
const Kitten = mongoose.model('Kitten', kittenSchema);
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'pug');
// uncomment after placing your favicon in /public
//app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
// our basic route to serve the index page
app.use('/', routes);
// the route where you can retrieve all the kittens in our MongoDB
app.get('/kittens', (req, res, next) => {
Kitten.find((err, kittens) => {
if (err) return next(err);
res.json(kittens);
})
})
// the route where you can create a new kitten in our MongoDB
app.post('/kittens', (req, res, next) => {
const kitten = new Kitten({
name: req.query.name
});
kitten.save((err, newKitten) => {
if (err) return next(err);
res.send('Kitten ' + newKitten.name + ' saved');
})
})
// catch 404 and forward to error handler
app.use((req, res, next) => {
const err = new Error('Not Found');
err.status = 404;
next(err);
});
// error handlers
// development error handler
// will print stacktrace
if (app.get('env') === 'development') {
app.use((err, req, res, next) => {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: err
});
});
}
// production error handler
// no stacktraces leaked to user
app.use((err, req, res, next) => {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: {}
});
});
module.exports = app;
```
This ensures that when you access your app using the `/kittens` route, it will return all the kittens stored in your database. Currently there are no kittens so it will return an empty array. Sad...
But you can create new kittens by POST-ing to the `/kittens` endpoint with the kitten's name as a URL query parameter. You can do so using curl or any similar tool:
<pre class="terminal">
$ curl -X POST "http://localhost:3000/kittens?name=garfield"
</pre>
and then retrieve your new kitten at the `GET /kittens` endpoint.
The line
```javascript
if (process.env.VCAP_SERVICES) {
```
checks if the app is running in the cloud. If not, it falls back to the default local MongoDB url. This allows you to run your app locally as well as in the cloud without having to configure anything differently. So let's push it to the cloud using
<pre class="terminal">
$ cf push my-nodejs-app
</pre>
You can access other services like Redis or MariaDB in a similar matter, simply by binding them to your app and accessing them through the environment variables.
<div style="text-align:center;padding:3em;">
<a href="./manifest.html" class="btn btn-primary">I've bound a service to my App</a>
</div>