Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /**
- * Module dependencies.
- */
- var express = require('express'),
- routes = require('./routes'),
- user = require('./routes/user'),
- http = require('http'),
- path = require('path'),
- fs = require('fs'),
- ibmbluemix = require('ibmbluemix'),
- ibmpush = require('ibmpush');
- var app = express();
- var db;
- var cloudant;
- var fileToUpload;
- var dbCredentials = {
- dbName : 'my_sample_db',
- dbProvider : 'provider'
- };
- var config = {
- // change to real application route assigned for your application
- applicationRoute : "http://demo.mybluemix.net"
- //for test by postman.
- };
- // init core sdk
- ibmbluemix.initialize(config);
- var ibmconfig = ibmbluemix.getConfig();
- var bodyParser = require('body-parser');
- var methodOverride = require('method-override');
- var logger = require('morgan');
- var errorHandler = require('errorhandler');
- var multipart = require('connect-multiparty');
- var multipartMiddleware = multipart();
- // all environments
- app.set('port', process.env.PORT || 3000);
- app.set('views', __dirname + '/views');
- app.set('view engine', 'ejs');
- app.engine('html', require('ejs').renderFile);
- app.use(logger('dev'));
- app.use(bodyParser.urlencoded({ extended: true }));
- app.use(bodyParser.json());
- app.use(methodOverride());
- app.use(express.static(path.join(__dirname, 'public')));
- app.use('/style', express.static(path.join(__dirname, '/views/style')));
- //CORS middleware
- var allowCrossDomain = function(req, res, next) {
- res.header('Access-Control-Allow-Origin', '*');
- res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE');
- 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');
- next();
- };
- app.use(allowCrossDomain);
- // development only
- if ('development' == app.get('env')) {
- app.use(errorHandler());
- }
- function initDBConnection() {
- if(process.env.VCAP_SERVICES) {
- var vcapServices = JSON.parse(process.env.VCAP_SERVICES);
- // Pattern match to find the first instance of a Cloudant service in
- // VCAP_SERVICES. If you know your service key, you can access the
- // service credentials directly by using the vcapServices object.
- for(var vcapService in vcapServices){
- if(vcapService.match(/cloudant/i)){
- dbCredentials.host = vcapServices[vcapService][0].credentials.host;
- dbCredentials.port = vcapServices[vcapService][0].credentials.port;
- dbCredentials.user = vcapServices[vcapService][0].credentials.username;
- dbCredentials.password = vcapServices[vcapService][0].credentials.password;
- dbCredentials.url = vcapServices[vcapService][0].credentials.url;
- cloudant = require('cloudant')(dbCredentials.url);
- // check if DB exists if not create
- cloudant.db.create(dbCredentials.dbName, function (err, res) {
- if (err) { console.log('could not create db ', err); }
- });
- db = cloudant.use(dbCredentials.dbName);
- break;
- }
- }
- if(db==null){
- console.warn('Could not find Cloudant credentials in VCAP_SERVICES environment variable - data will be unavailable to the UI');
- }
- } else{
- console.warn('VCAP_SERVICES environment variable not set - data will be unavailable to the UI');
- }
- }
- initDBConnection();
- app.get('/', routes.index);
- function createResponseData(id, name, phone, attachments) {
- var responseData = {
- id : id,
- name : name,
- phone : phone,
- attachements : []
- };
- attachments.forEach (function(item, index) {
- var attachmentData = {
- content_type : item.type,
- key : item.key,
- url : '/api/favorites/attach?id=' + id + '&key=' + item.key
- };
- responseData.attachements.push(attachmentData);
- });
- return responseData;
- }
- function createResponseDataProvider(id, provider_type, name, phone, mobile, email, logo, address) {
- var responseData = {
- id : id,
- provider_type: provider_type,
- name : name,
- phone : phone,
- mobile: mobile,
- email: email,
- logo: logo,
- address : address
- };
- return responseData;
- }
- //=============get api/rovider/:id================
- app.use(ibmconfig.getContextRoot(), require('./lib/provider'));
- http.createServer(app).listen(app.get('port'), '0.0.0.0', function() {
- console.log('Express server listening on port ' + app.get('port'));
- });
- var router = require('express').Router();
- //create del all whitespace of string function
- String.prototype.delAllWhiteSpace = function() {
- return this.split(' ').join('');
- };
- var Providers = {
- getProvider: function(req, res){
- db = cloudant.use(dbCredentials.dbProvider);
- var docList = [];
- var i = 0;
- db.list(function(err, body) {
- if (!err) {
- var len = body.rows.length;
- console.log('total # of docs -> '+len);
- if(len == 0) {
- // error
- } else {
- body.rows.forEach(function(document) {
- db.get(document.id, { revs_info: true }, function(err, doc) {
- if (!err) {
- if(doc['_attachments']) {
- // todo
- } else {
- var responseData = createResponseDataProvider(
- doc._id,
- doc.provider_type,
- doc.name,
- doc.phone,
- doc.mobile,
- doc.email,
- doc.logo,
- doc.address
- );
- }
- docList.push(responseData);
- i++;
- if(i >= len) {
- response.write(JSON.stringify(docList));
- console.log('ending response...');
- response.end();
- }
- } else {
- console.log(err);
- }
- });
- });
- }
- } else {
- console.log(err);
- }
- });
- }
- };
- router.get('/abc/provider/', Providers.getProvider);
- module.exports = exports = router;
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement