forked from cloudendpoints/esp
-
Notifications
You must be signed in to change notification settings - Fork 0
/
bookstore.js
405 lines (356 loc) · 11.2 KB
/
bookstore.js
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
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
// Copyright (C) Extensible Service Proxy Authors
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// 1. Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// 2. Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
//
// THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
// OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
// HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
// LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
// OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
// SUCH DAMAGE.
//
////////////////////////////////////////////////////////////////////////////////
//
// A Google Cloud Endpoints example implementation of a simple bookstore API.
'use strict';
var express = require('express');
var bodyParser = require('body-parser');
var swaggerTools = require('swagger-tools');
/**
* @typedef {Object} InitializationOptions
* @property {Boolean} log Log incoming requests.
* @property {Object} swagger Swagger document object.
*/
/**
* Creates an Express.js application which implements a Bookstore
* API defined in `swagger.json`.
*
* @param {InitializationOptions} options Application initialization options.
* @return {!express.Application} An initialized Express.js application.
*
* If no options are provided, defaults are:
* {
* log: true,
* }
*/
function bookstore(options) {
options = options || {
log: true,
};
var app = express();
app.use(bodyParser.json());
// Serve application version for tests to ensure that
// bookstore was deployed correctly.
app.get('/version', function(req, res) {
res.set('Content-Type', 'application/json');
res.status(200).send({
version: '${VERSION}'
});
});
var echoCount = 0;
// Echo method for stress test.
function echo(req, res) {
echoCount += 1;
res.status(200).json(req.body);
}
app.all('/echo', echo);
app.get('/echo/auth', echo);
app.post('/echo/auth', echo);
// Show number of echo requests
setInterval(function() {
if (echoCount > 0) {
var date = new Date();
var timestamp = date.getHours() + ":" + date.getMinutes() + ":" +
date.getSeconds() + ":" + date.getMilliseconds();
console.log(timestamp + ' Echo requests received: ', echoCount);
}
}, 1000);
// Install tracing middleware.
if (options.log === true) {
app.use(function(req, res, next) {
console.log(req.method, req.originalUrl);
next();
});
}
if (options.swagger) {
// Initialize the Swagger UI middleware.
swaggerTools.initializeMiddleware(options.swagger, function(middleware) {
// Serve the Swagger documents and Swagger UI.
app.use(middleware.swaggerUi());
});
}
// The bookstore example uses a simple, in-memory database
// for illustrative purposes only.
var bookstoreDatabase = {
shelves: {},
id: 0
};
function createShelf(theme) {
var id = ++bookstoreDatabase.id;
var shelf = {
name: 'shelves/' + id,
theme: theme,
books: {}
};
bookstoreDatabase.shelves[shelf.name] = shelf;
return shelf;
}
function getShelf(name) {
return bookstoreDatabase.shelves[name];
}
function deleteShelf(name) {
var shelf = bookstoreDatabase.shelves[name];
if (shelf === undefined) {
return undefined;
}
delete bookstoreDatabase.shelves[name];
return shelf;
}
function createBook(shelfName, author, title) {
var shelf = getShelf(shelfName);
if (shelf === undefined) {
return undefined;
}
var id = ++bookstoreDatabase.id;
var book = {
name: shelf.name + '/books/' + id,
author: author,
title: title
};
shelf.books[book.name] = book;
return book;
}
function getBook(shelfName, bookName) {
var shelf = getShelf(shelfName);
if (shelf === undefined) {
return undefined;
}
return shelf.books[bookName];
}
function deleteBook(shelfName, bookName) {
var shelf = getShelf(shelfName);
if (shelf === undefined) {
return undefined;
}
var book = shelf.books[bookName];
if (book === undefined) {
return undefined;
}
delete shelf.books[bookName];
return book;
}
/**
* @typedef {Object} UserInfo
* @property {String} id An auth provider defined user identity.
* @property {String} email An authenticated user email address.
* @property {Object} consumer_id A consumer identifier (currently unused).
*/
/**
* Extracts from the request headers user information attached
* by Endpoints.
*
* An example of the result (all properties are optional):
* {
* id: 'xxx',
* email: 'xxx',
* consumer_id: 'xxx'
* }
*
* @param {!express.Request} req An Express.js Request object.
* @return {!UserInfo} An authenticated user information.
*/
function getUserInfo(req) {
var header = req.get('X-Endpoint-API-UserInfo');
if (header) {
return JSON.parse(new Buffer(header, 'base64').toString());
}
return {};
}
function error(res, status, message) {
res.status(status).json({
error: status,
message: message
});
}
app.get('/', function(req, res) {
res.status(200).sendFile('index.html', {
root: __dirname
});
});
app.get('/restricted', function(req, res) {
res.status(200).json({
msg: 'restricted'
});
});
app.get('/quota_read', function(req, res) {
res.status(200).json({
msg: 'ok'
});
});
app.get('/shelves', function(req, res) {
var shelves = bookstoreDatabase.shelves;
var result = [];
for (var name in shelves) {
var shelf = shelves[name];
result.push({
name: shelf.name,
theme: shelf.theme
});
}
res.status(200).json({
shelves: result
});
});
app.post('/shelves', function(req, res) {
var shelfRequest = req.body;
if (shelfRequest === undefined) {
return error(res, 400, 'Missing request body.');
}
if (shelfRequest.theme === undefined) {
return error(res, 400, 'Shelf resource is missing required \'theme\'.');
}
var shelf = createShelf(shelfRequest.theme);
res.status(200).json({
name: shelf.name,
theme: shelf.theme
});
});
app.get('/shelves/:shelf', function(req, res) {
var shelf = getShelf('shelves/' + req.params.shelf);
if (shelf === undefined) {
return error(res, 404, 'Cannot find shelf shelves/' + req.params.shelf);
}
res.status(200).json({
name: shelf.name,
theme: shelf.theme
});
});
app.delete('/shelves/:shelf', function(req, res) {
var shelf = deleteShelf('shelves/' + req.params.shelf);
if (shelf === undefined) {
return error(res, 404, 'Cannot find shelf shelves/' + req.params.shelf);
}
res.status(204).end();
});
app.get('/shelves/:shelf/books', function(req, res) {
var shelf = getShelf('shelves/' + req.params.shelf);
if (shelf === undefined) {
return error(res, 404, 'Cannot find shelf shelves/' + req.params.shelf);
}
var books = shelf.books;
var result = [];
for (var name in books) {
var book = books[name];
result.push({
name: book.name,
author: book.author,
title: book.title
});
}
res.status(200).json({
books: result
});
});
app.post('/shelves/:shelf/books/', function(req, res) {
var bookRequest = req.body;
if (bookRequest === undefined) {
return error(res, 400, 'Missing request body.');
}
if (bookRequest.author === undefined) {
return error(res, 400, 'Book resource is missing required \'author\'.');
}
if (bookRequest.title === undefined) {
return error(res, 400, 'Book resource is missing required \'title\'.');
}
var shelf = getShelf('shelves/' + req.params.shelf);
if (shelf === undefined) {
return error(res, 404, 'Cannot find shelf shelves/' + req.params.shelf);
}
var book = createBook('shelves/' + req.params.shelf,
bookRequest.author,
bookRequest.title);
res.status(200).json({
name: book.name,
author: book.author,
title: book.title
});
});
app.get('/shelves/:shelf/books/:book', function(req, res) {
var book = getBook(
'shelves/' + req.params.shelf,
'shelves/' + req.params.shelf + '/books/' + req.params.book);
if (book === undefined) {
return error(res, 404, 'Cannot find book ' +
'shelves/' + req.params.shelf + '/books/' + req.params.book);
}
res.status(200).json({
name: book.name,
author: book.author,
title: book.title
});
});
app.delete('/shelves/:shelf/books/:book', function(req, res) {
var book = deleteBook(
'shelves/' + req.params.shelf,
'shelves/' + req.params.shelf + '/books/' + req.params.book);
if (book === undefined) {
return error(
res, 404, 'Cannot find book ' +
'shelves/' + req.params.shelf + '/books/' + req.params.book);
}
res.status(204).end();
});
// Initialize bookstoreDatabase
(function() {
// Initialize Bookstore
var fiction = createShelf('Fiction');
var fantasy = createShelf('Fantasy');
createBook(fiction.name, 'Neal Stephenson', 'REAMDE');
createBook(fantasy.name, 'George R.R. Martin', 'A Game of Thrones');
})();
return app;
}
function loadSwagger(port) {
var swagger = require('./swagger.json');
// When not running on Google App Engine and if the swagger.host
// has its default value (which is an invalid value), update the
// host to localhost and change schemes to [ 'http' ] to enable the
// Swagger UI.
var gae = 'Google App Engine/';
var ssw = process.env.SERVER_SOFTWARE;
if ((!ssw || ssw.substring(0, gae.length) !== gae) &&
swagger.host === '${MY_PROJECT_ID}.appspot.com') {
swagger.host = 'localhost:' + port;
swagger.schemes = [ 'http' ];
}
return swagger;
}
// If this file is imported as a module, export the `bookstore` function.
// Otherwise, if `bookstore.js` is executed as a main program, start
// the server and listen on a port.
if (module.parent) {
module.exports = bookstore;
} else {
var port = process.env.PORT || '8080';
var swagger = loadSwagger(port);
var server = bookstore({ log: false, swagger: swagger }).listen(port, '0.0.0.0',
function() {
var host = server.address().address;
var port = server.address().port;
console.log('Bookstore listening at http://%s:%s', host, port);
}
);
}