Advertisement
Guest User

Untitled

a guest
Nov 5th, 2016
107
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 6.22 KB | None | 0 0
  1. /**
  2. * Module dependencies.
  3. */
  4.  
  5. var express = require('express'),
  6. routes = require('./routes'),
  7. user = require('./routes/user'),
  8. http = require('http'),
  9. path = require('path'),
  10. fs = require('fs'),
  11. ibmbluemix = require('ibmbluemix'),
  12. ibmpush = require('ibmpush');
  13.  
  14.  
  15.  
  16. var app = express();
  17.  
  18. var db;
  19.  
  20. var cloudant;
  21.  
  22. var fileToUpload;
  23.  
  24. var dbCredentials = {
  25. dbName : 'my_sample_db',
  26. dbProvider : 'provider'
  27.  
  28. };
  29.  
  30. var config = {
  31. // change to real application route assigned for your application
  32. applicationRoute : "http://demo.mybluemix.net"
  33. //for test by postman.
  34. };
  35.  
  36. // init core sdk
  37. ibmbluemix.initialize(config);
  38. var ibmconfig = ibmbluemix.getConfig();
  39.  
  40. var bodyParser = require('body-parser');
  41. var methodOverride = require('method-override');
  42. var logger = require('morgan');
  43. var errorHandler = require('errorhandler');
  44. var multipart = require('connect-multiparty');
  45. var multipartMiddleware = multipart();
  46.  
  47. // all environments
  48. app.set('port', process.env.PORT || 3000);
  49. app.set('views', __dirname + '/views');
  50. app.set('view engine', 'ejs');
  51. app.engine('html', require('ejs').renderFile);
  52. app.use(logger('dev'));
  53. app.use(bodyParser.urlencoded({ extended: true }));
  54. app.use(bodyParser.json());
  55. app.use(methodOverride());
  56. app.use(express.static(path.join(__dirname, 'public')));
  57. app.use('/style', express.static(path.join(__dirname, '/views/style')));
  58.  
  59. //CORS middleware
  60. var allowCrossDomain = function(req, res, next) {
  61. res.header('Access-Control-Allow-Origin', '*');
  62. res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE');
  63. res.header('Access-Control-Allow-Headers', 'Content-type,Accept,X-Access-Token,X-Key,IBM-APPLICATION-SECRET,IBM-APPLICATION-ID,IBM-DEVICE-MODEL,IBM-DEVICE-TYPE,IBM-DEVICE-ID,IBM-DEVICE-PLATFORM-VERSION, IBM-DEVICE-NAME,IBM-REQUEST-CORRELATION-ID,X-REWRITE-DOMAIN');
  64.  
  65. next();
  66. };
  67. app.use(allowCrossDomain);
  68. // development only
  69. if ('development' == app.get('env')) {
  70. app.use(errorHandler());
  71. }
  72.  
  73. function initDBConnection() {
  74.  
  75. if(process.env.VCAP_SERVICES) {
  76. var vcapServices = JSON.parse(process.env.VCAP_SERVICES);
  77. // Pattern match to find the first instance of a Cloudant service in
  78. // VCAP_SERVICES. If you know your service key, you can access the
  79. // service credentials directly by using the vcapServices object.
  80. for(var vcapService in vcapServices){
  81. if(vcapService.match(/cloudant/i)){
  82. dbCredentials.host = vcapServices[vcapService][0].credentials.host;
  83. dbCredentials.port = vcapServices[vcapService][0].credentials.port;
  84. dbCredentials.user = vcapServices[vcapService][0].credentials.username;
  85. dbCredentials.password = vcapServices[vcapService][0].credentials.password;
  86. dbCredentials.url = vcapServices[vcapService][0].credentials.url;
  87.  
  88. cloudant = require('cloudant')(dbCredentials.url);
  89.  
  90. // check if DB exists if not create
  91. cloudant.db.create(dbCredentials.dbName, function (err, res) {
  92. if (err) { console.log('could not create db ', err); }
  93. });
  94.  
  95. db = cloudant.use(dbCredentials.dbName);
  96. break;
  97. }
  98. }
  99. if(db==null){
  100. console.warn('Could not find Cloudant credentials in VCAP_SERVICES environment variable - data will be unavailable to the UI');
  101. }
  102. } else{
  103. console.warn('VCAP_SERVICES environment variable not set - data will be unavailable to the UI');
  104.  
  105. }
  106. }
  107.  
  108. initDBConnection();
  109.  
  110. app.get('/', routes.index);
  111.  
  112. function createResponseData(id, name, phone, attachments) {
  113.  
  114. var responseData = {
  115. id : id,
  116. name : name,
  117. phone : phone,
  118. attachements : []
  119. };
  120.  
  121. attachments.forEach (function(item, index) {
  122. var attachmentData = {
  123. content_type : item.type,
  124. key : item.key,
  125. url : '/api/favorites/attach?id=' + id + '&key=' + item.key
  126. };
  127. responseData.attachements.push(attachmentData);
  128.  
  129. });
  130. return responseData;
  131. }
  132.  
  133. function createResponseDataProvider(id, provider_type, name, phone, mobile, email, logo, address) {
  134.  
  135. var responseData = {
  136. id : id,
  137. provider_type: provider_type,
  138. name : name,
  139. phone : phone,
  140. mobile: mobile,
  141. email: email,
  142. logo: logo,
  143. address : address
  144. };
  145.  
  146. return responseData;
  147. }
  148.  
  149.  
  150.  
  151.  
  152. //=============get api/rovider/:id================
  153.  
  154. app.use(ibmconfig.getContextRoot(), require('./lib/provider'));
  155.  
  156. http.createServer(app).listen(app.get('port'), '0.0.0.0', function() {
  157. console.log('Express server listening on port ' + app.get('port'));
  158. });
  159.  
  160. var router = require('express').Router();
  161. //create del all whitespace of string function
  162. String.prototype.delAllWhiteSpace = function() {
  163. return this.split(' ').join('');
  164. };
  165. var Providers = {
  166. getProvider: function(req, res){
  167.  
  168. db = cloudant.use(dbCredentials.dbProvider);
  169. var docList = [];
  170. var i = 0;
  171. db.list(function(err, body) {
  172. if (!err) {
  173. var len = body.rows.length;
  174. console.log('total # of docs -> '+len);
  175. if(len == 0) {
  176. // error
  177. } else {
  178. body.rows.forEach(function(document) {
  179. db.get(document.id, { revs_info: true }, function(err, doc) {
  180. if (!err) {
  181. if(doc['_attachments']) {
  182. // todo
  183. } else {
  184. var responseData = createResponseDataProvider(
  185. doc._id,
  186. doc.provider_type,
  187. doc.name,
  188. doc.phone,
  189. doc.mobile,
  190. doc.email,
  191. doc.logo,
  192. doc.address
  193. );
  194. }
  195. docList.push(responseData);
  196. i++;
  197. if(i >= len) {
  198. response.write(JSON.stringify(docList));
  199. console.log('ending response...');
  200. response.end();
  201. }
  202. } else {
  203. console.log(err);
  204. }
  205. });
  206.  
  207. });
  208. }
  209.  
  210. } else {
  211. console.log(err);
  212. }
  213. });
  214.  
  215. }
  216. };
  217.  
  218. router.get('/abc/provider/', Providers.getProvider);
  219. module.exports = exports = router;
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement