Beispiel #1
0
 constructor(
   opts: RouterOptions
 ) {
   this.server   = opts.server || restify.createServer(opts);
   this.port     = opts.port || 8080;
   this.hostname = opts.hostname || null;
 }
Beispiel #2
0
      stats).then((managedAccessKeyRepository) => {
    const managerService = new ShadowsocksManagerService(managedAccessKeyRepository);
    const certificateFilename = process.env.SB_CERTIFICATE_FILE;
    const privateKeyFilename = process.env.SB_PRIVATE_KEY_FILE;

    // TODO(bemasc): Remove casts once https://github.com/DefinitelyTyped/DefinitelyTyped/pull/15229 lands
    const apiServer = restify.createServer({
      certificate: fs.readFileSync(certificateFilename),
      key: fs.readFileSync(privateKeyFilename)
    });

    // Pre-routing handlers
    apiServer.pre(restify.CORS());

    // All routes handlers
    const apiPrefix = process.env.SB_API_PREFIX ? `/${process.env.SB_API_PREFIX}` : '';
    apiServer.pre(restify.pre.sanitizePath());
    apiServer.use(restify.jsonp());
    apiServer.use(restify.bodyParser());
    setApiHandlers(apiServer, apiPrefix, managerService, stats, serverConfig);

    // TODO(fortuna): Bind to localhost or unix socket to avoid external access.
    apiServer.listen(portNumber, () => {
      logging.info(`Manager listening at ${apiServer.url}${apiPrefix}`);
    });
  });
Beispiel #3
0
bot.setup().then(() => {

    // Listen to activities sent to the bot
    const server = restify.createServer();
    server.use(restify.plugins.queryParser());
    server.listen(process.env.port || process.env.PORT || 3977, function () {
        console.log('%s listening to %s', server.name, server.url);
    });
    server.post('/api/messages', connector.listen());
});
Beispiel #4
0
/**
 * Start the server and return its URL.
 */
function serve(log: (msg: any) => any): Promise<string> {
  let server = restify.createServer();
  let qp = restify.queryParser({ mapParams: false });

  // Log messages to a file.
  server.get('/log', qp, (req: any, res: any, next: any) => {
    let out = log(JSON.parse(req.query['msg']));
    res.send(out);
    return next();
  });

  // Serve the main HTML and JS files.
  server.get('/', restify.serveStatic({
    // `directory: '.'` appears to be broken:
    // https://github.com/restify/node-restify/issues/549
    directory: '../harness',
    file: 'index.html',
    maxAge: 0,
  }));
  server.get('/client.js', restify.serveStatic({
    directory: './build',
    file: 'client.js',
    maxAge: 0,
  }));

  // Serve the dingus assets.
  server.get(/\/.*/, restify.serveStatic({
    directory: '../dingus',
    default: 'index.html',
    maxAge: 0,
  }));

  // Show errors. This should be a Restify default.
  server.on('uncaughtException', (req: any, res: any, route: any, err: any) => {
    if (err.stack) {
      console.error(err.stack);
    } else {
      console.error(err);
    }
  });

  // More filling in the blanks: log each request as it comes in.
  server.on('after', (req: any, res: any, route: any, err: any) => {
    plog(res.statusCode + " " + req.method + " " + req.url);
  });

  // Start the server.
  let port = 4700;
  let url = "http://localhost:" + port;
  return new Promise((resolve, reject) => {
    server.listen(port, () => {
      resolve(url);
    });
  });
}
    constructor(name: string) {
        this.router = Restify.createServer({
            name: name
        });

        this.router.on('listening', () => {
            log.debug(`${this.router.name} listening on ${this.router.url}`);
        });

        this.router.use(Restify.acceptParser(this.router.acceptable));
        this.router.use(stripEmptyBearerToken);
        this.router.use(Restify.dateParser());
        this.router.use(Restify.queryParser());
    }
Beispiel #6
0
        constructor(){

            // Setup Restify Server
            this._server = restify.createServer();
            this._server.listen(process.env.port || process.env.PORT || 3978, () => {
                console.log('%s listening to %s', this._server.name, this._server.url); 
            });
            
            // Create chat bot
            this._botConnector = new builder.ChatConnector({
                appId: process.env.MICROSOFT_APP_ID,
                appPassword: process.env.MICROSOFT_APP_PASSWORD
            });

            this._bot = new builder.UniversalBot(this._botConnector);
            this._server.post('/api/messages', this._botConnector.listen());

            //Init dialogs
            this._dialogsmanager = new BOT.RETAILBOT.DialogsManager();
            this._dialogsmanager.init(this._bot);
        }
Beispiel #7
0
/**
 * Start the server and return its URL.
 */
function serve(log: (msg: any) => void): Promise<string> {
  let server = restify.createServer();
  let qp = restify.queryParser({ mapParams: false });

  // Log messages to a file.
  server.get('/log', qp, (req: any, res: any, next: any) => {
    log(JSON.parse(req.query['msg']));
    res.send('done');
    next();
  });

  // Serve the main HTML and JS files.
  server.get('/', restify.serveStatic({
    // `directory: '.'` appears to be broken:
    // https://github.com/restify/node-restify/issues/549
    directory: '../harness',
    file: 'index.html',
  }));
  server.get('/client.js', restify.serveStatic({
    directory: './build',
    file: 'client.js',
  }));

  // Serve the dingus assets.
  server.get(/\/.*/, restify.serveStatic({
    directory: '../dingus',
    default: 'index.html',
  }));

  // Start the server.
  let port = 4700;
  let url = "http://localhost:" + port;
  return new Promise((resolve, reject) => {
    server.listen(port, () => {
      resolve(url);
    });
  });
}
import * as restify from "restify";
import * as url from "url";
import * as Logger from "bunyan";
import * as http from "http";
import * as stream from "stream";

let server: restify.Server;

server = restify.createServer({
    formatters: {
        'application/foo': function formatFoo(req: restify.Request, res: restify.Response, body: any) {
            if (body instanceof Error)
                return body.stack;

            if (body)
                return body.toString('base64');

            return body;
        }
    }
});

server = restify.createServer({});

server.pre(restify.pre.sanitizePath());

server.on('someEvent', () => { });

server.use((req: restify.Request, res: restify.Response, next: restify.Next) => { });
server.use([(req: restify.Request, res: restify.Response, next: restify.Next) => { }, (req: restify.Request, res: restify.Response, next: restify.Next) => { }]);
server.use((req: restify.Request, res: restify.Response, next: restify.Next) => { }, (req: restify.Request, res: restify.Response, next: restify.Next) => { });
Beispiel #9
0
/// <reference path="../typings/index.d.ts" />

import * as restify from 'restify';

let server = restify.createServer({
  name: 'img-server',
  version: '1.0.0',
});

server.use(restify.acceptParser(server.acceptable));
server.use(restify.queryParser());
server.use(restify.bodyParser({
  maxBodySize: 0,
  mapParams: true,
  mapFiles: true,
  overrideParams: true,
  keepExtensions: true,
  multiples: true,
  hash: 'sha1'
}));
server.use(restify.gzipResponse());
server.use(restify.throttle({
  burst: 100,
  rate: 50,
  ip: true,
  overrides: {
    '192.168.1.1': {
      rate: 0,        // unlimited
      burst: 0
    },
    "127.0.0.1": {
Beispiel #10
0
import * as restify from 'restify';
import * as fs from 'fs';
import {settings} from './config';
import {logger} from './logger';
import * as auth from './core/auth';

var server = restify.createServer({
    name: settings.name,
    log: logger
});

restify.CORS.ALLOW_HEADERS.push('authorization');
server.use(restify.CORS());
server.pre(restify.pre.sanitizePath());
server.use(restify.acceptParser(server.acceptable));
server.use(restify.bodyParser());
server.use(restify.queryParser());
server.use(restify.authorizationParser());
server.use(restify.fullResponse());
server.use(auth.Auth());

fs.readdirSync(__dirname + '/routes').forEach(function (routeConfig:string) {
    if (routeConfig.substr(-3) === '.js') {
        var route = require(__dirname + '/routes/' + routeConfig);
        route.routes(server);
    }
});

server.listen(settings.port, function () {
    console.log(`INFO: ${settings.name} is running at ${server.url}`);
});
import * as restify from 'restify';
import { IProduct, products } from './products';

const server: restify.Server = restify.createServer();
const port: number = 3000;

server.use(restify.plugins.bodyParser());

server.get('/api/products', (request: restify.Request, response: restify.Response) => {
  console.log(products);
  response.json(products);
});

server.get('/api/products/:id', (request: restify.Request, response: restify.Response) => {
  const id = Number(request.params.id);
  const product = products.filter(product => product.id === id);
  response.json(product);
});

server.post('/api/products', (request: restify.Request, response: restify.Response) => {
  const newProduct: IProduct = request.body;
  products.push(newProduct);
  response.json(products);
});

server.listen(port, () => console.info(`REST API is running on port ${port}`));
Beispiel #12
0
/// <reference path="../typings/browser.d.ts" />

import {easLogin} from './data';

var restify = require('restify');

function respond(req, res, next) {
    res.send('hello ' + req.params.name);
    next();
}

var server = restify.createServer({
    name: 'eas2rest'
});
server.get('/hello/:name', respond);
server.head('/hello/:name', respond);

server.listen(2979, function () {
    console.log('%s listening at %s', server.name, server.url);

    var result = easLogin('xiaxy', 'xxy123');
});
import logger from "./logging.config";

import * as restify from "restify";
import {Server} from "restify";

import {registerActionsInExpressApp} from "controllers.ts/Factory";
import {ControllerRunner} from "controllers.ts/ControllerRunner";

let config = require("../../package.json");
let port = process.env.PORT || 3000;
let host = process.env.HOST || "localhost";

logger.info("Setting up restify...");

const server: Server = restify.createServer({
    name: config.name,
    version: config.version
});

server.pre(restify.pre.sanitizePath());

const controllerRunner: ControllerRunner = registerActionsInExpressApp(server, [__dirname + "/../api"]);
controllerRunner.container = {
    get: function (someClass: any): any {
        logger.info("Setting up restify...");
        return kernel.get(someClass.name);
    }
};


server.listen(port, host, () => logger.info(`${server.name}@${config.version} listening at ${host}:${port}`));
Beispiel #14
0
import { createServer } from 'restify';
import { ChatConnector, IEvent, IntentDialog, Message, Prompts, UniversalBot } from 'botbuilder';

const server = createServer();
server.listen(process.env.PORT || 3978, () => console.log('%s listening to %s', server.name, server.url));

let connector = new ChatConnector({
    appId: process.env.MICROSOFT_APP_ID,
    appPassword: process.env.MICROSOFT_APP_PASSWORD
});

let bot = new UniversalBot(connector);
server.post('/api/messages', connector.listen());

bot.on('installationUpdate', (activity: IEvent) => {
    let token = activity.sourceEvent.token;
    
    let message = new Message()
        .address(activity.address)
        .text(token);

    bot.send(message);
});

let intents = new IntentDialog();
bot.dialog('/', intents);

intents.matches(/^hello/, [
    (session) => session.beginDialog('/hello')
]);
Beispiel #15
0
import * as restify from 'restify';

import app from './app';
import config from './config';
//创建http server
let server: restify.Server = restify.createServer({
    name: 'docs-search_server'
});
server.use(restify.gzipResponse());//gzip压缩
server.use(restify.bodyParser());//将post请求的body数据转化到req.params
server.use(restify.queryParser());//将url?后的参数转化到req.params
// server.get(/\/docs\/public\/?.*/, restify.serveStatic({
//     directory: '../public'
// }));
//http服务器错误捕捉
// server.on('err', function (err) {
//     mongoose.disconnect(function (err) {
//         console.log('mongoose was disconnected');
//     });
//     console.log('server has a error, and stoped');
// });

//开始监听
server.listen(config.API_PORT, function () {
    console.log("%s listening at %s", server.name, server.url);
});
app(server);
Beispiel #16
0
import * as restify from 'restify'
import things from '../api/things/index'

let hippie = require('hippie')
let app = restify.createServer()
things(app)

describe("Things API", () => {
  describe("/things endpoint", () => {
    it("should return 200", done => {
      hippie(app)
        .json()
        .get('/things')
        .expectStatus(200)
        .end((err, res, body) => {
          err && done.fail(err)
          app.close()
        })
    })
  })
})

 /**
  * Wrapper for the restify server.
  *
  * @param container Container loaded with all controllers and their dependencies.
  */
 constructor(container: inversify.interfaces.Container, opts?: restify.ServerOptions) {
     this.container = container;
     this.app = restify.createServer(opts);
 }
Beispiel #18
0
export const strapFramework = (kwargs: IStrapFramework) => {
    if (kwargs.root == null) kwargs.root = '/api';
    if (kwargs.skip_app_logging == null) kwargs.skip_app_logging = true;
    if (kwargs.skip_app_version_routes == null) kwargs.skip_app_version_routes = true;
    if (kwargs.skip_start_app == null) kwargs.skip_start_app = false;
    else if (kwargs.listen_port == null) /* tslint:disable:no-bitwise */
        kwargs.listen_port = typeof process.env['PORT'] === 'undefined' ? 3000 : ~~process.env['PORT'];

    Object.keys(kwargs.orms_in).map(orm => {
        if (kwargs.orms_in[orm].skip == null) kwargs.orms_in[orm].skip = true;
    });
    if (kwargs.orms_in.redis != null && !kwargs.orms_in.redis.skip && kwargs.orms_in.redis.config == null)
        kwargs.orms_in.redis.config = process.env['REDIS_URL'] == null ? { port: 6379 } : process.env['REDIS_URL'];

    // Init server obj
    const app = restify.createServer(Object.assign({ name: kwargs.app_name }, kwargs.createServerArgs || {}));

    app.use(queryParser());
    app.use(bodyParser());

    app.on('WLError', (req: restify.Request, res: restify.Response,
                       err: Waterline.WLError, next: restify.Next) =>
        next(new WaterlineError(err))
    );

    if (!kwargs.skip_app_logging)
        app.on('after', auditLogger({
            log: Logger.createLogger({
                name: 'audit',
                stream: process.stdout
            })
        }));

    if (!kwargs.skip_app_version_routes)
        ['/', '/version', '/api', '/api/version'].map(route_path => app.get(route_path,
            (req: restify.Request, res: restify.Response, next: restify.Next) => {
                res.json({ version: kwargs.package_.version });
                return next();
            }
        ));

    const routes = new Set<string>();
    const norm = new Set<string>();
    const waterline_set = new Set<any /*program*/>();
    const typeorm_map = new Map<string, any /*program*/>();
    const sequelize_map = new Map<string, any /*program*/>();

    const do_models: boolean = Object
        .keys(kwargs.orms_in)
        .filter(orm => orm !== 'Redis')
        .some(orm => kwargs.orms_in[orm].skip === false);

    if (!(kwargs.models_and_routes instanceof Map))
        kwargs.models_and_routes = model_route_to_map(kwargs.models_and_routes);
    for (const [fname, program] of kwargs.models_and_routes as Map<string, any>)
        if (program != null)
            if /* Merge models */ (fname.indexOf('model') > -1 && do_models)
                populateModels(
                    program, kwargs.omit_models || ['AccessToken'], norm,
                    waterline_set, typeorm_map, sequelize_map
                );
            else /* Merge routes */ /* tslint:disable:no-unused-expression */
                typeof program === 'object' && Object.keys(program).map((route: string) =>
                    (program[route] as ((app: restify.Server, namespace: string) => void))(
                        app, `${kwargs.root}/${dirname(fname)}`
                    )
                ) && routes.add(dirname(fname));

    kwargs.logger.info('Restify registered routes:\t', Array.from(routes.keys()), ';');
    kwargs.logger.warn('Failed registering models:\t', Array.from(norm.keys()), ';');

    parallel({
        redis: cb => kwargs.orms_in.redis == null ? cb(void 0) :
            redisHandler(kwargs.orms_in.redis, kwargs.logger, cb),
        sequelize: cb => kwargs.orms_in.sequelize == null ? cb(void 0) :
            sequelizeHandler(Object.assign(kwargs.orms_in.sequelize, { map: sequelize_map }), kwargs.logger, cb),
        typeorm: cb => kwargs.orms_in.typeorm == null ? cb(void 0) :
            typeormHandler(Object.assign(kwargs.orms_in.typeorm, { map: typeorm_map }), kwargs.logger, cb),
        waterline: cb => kwargs.orms_in.waterline == null ? cb(void 0) :
            waterlineHandler(Object.assign(kwargs.orms_in.waterline, { set: waterline_set }), kwargs.logger, cb),
    }, (err: Error, orms_out: IOrmsOut) => {
        if (err != null) {
            if (kwargs.callback) return kwargs.callback(err);
            throw err;
        }
        return handleStartApp(
            kwargs.skip_start_app, app, kwargs.listen_port, kwargs.onServerStart,
            kwargs.logger, orms_out, kwargs.callback
        );
    });
};
 constructor(private restifyContactRouter: RestifyContactRouter) {
   console.log("RestifyApplication ctor");
   // create restify server
   this.restifyApplication = restify.createServer();
 }
import * as restify from "restify";
import * as url from "url";

let server = restify.createServer({
    formatters: {
        'application/foo': function formatFoo(req: restify.Request, res: restify.Response, body: any) {
            if (body instanceof Error)
                return body.stack;

            if (body)
                return body.toString('base64');

            return body;
        }
    }
});

server = restify.createServer({
    ca: "test",
    certificate: "test",
    key: "test",
    formatters: {},
    log: {},
    name: "test",
    spdy: {},
    version: "",
    responseTimeHeader: "",
    responseTimeFormatter: (durationInMilliseconds: number) => { },
    socketio: false
});
Beispiel #21
0
 constructor(private config) {
     this.server = restify.createServer()
     this.server.use(restify.bodyParser())
 }
Beispiel #22
0
}

const tokenGenerator = new FirebaseTokenGenerator(firebaseSecret);
const token = tokenGenerator.createToken({ uid: firebaseUid, version: '1.0' });

const firebaseRef = new Firebase("https://colorqueue.firebaseio.com");
firebaseRef.authWithCustomToken(token, (error, authData) => {
  if (error) {
    throw error;
  }
  
  console.log("Login Succeeded!", authData);
});

const server = restify.createServer({
  name: 'ColorQueue'
});
server.use(restify.acceptParser(server.acceptable));
server.use(restify.CORS());
server.use(restify.queryParser());
server.use(restify.bodyParser());

server.post('/colors', function create(req, res, next) {
  const {r, g, b, a} = req.body;
  const timestamp = (new Date()).getTime();
  const body = {
    r,
    g,
    b,
    a,
    order: timestamp,
Beispiel #23
0
import * as restify from "restify";
import * as routes from "./routes";

//config
export const server = restify.createServer({
    name: 'docdb-connector',
    version: '0.1.0'
});

const port = process.env.port || 8000;

//parsing settings
server.use(restify.acceptParser(server.acceptable));
server.use(restify.queryParser());
server.use(restify.bodyParser());
server.pre(restify.pre.sanitizePath());
server.use(restify.dateParser());

//call the routes.ts file for available REST API routes
routes.setRoutes(server);

//when running the app will listen locally to port 51234
server.listen(port, function() {
    console.log('%s listening at %s', server.name, server.url);
})

Beispiel #24
0
import * as Bunyan from "bunyan";
import * as Restify from "restify";
import {Routes} from "./routes";

let applicationName: string = "heroku-world";

let log: Bunyan.Logger = Bunyan.createLogger({
    name: applicationName,
});

let server: Restify.Server = Restify.createServer({
    log: log,
    name: applicationName,
    version: "0.0.1",
});

server.use(Restify.acceptParser(server.acceptable));
server.use(Restify.queryParser());
server.use(Restify.bodyParser());

// setup the logging.
interface IAuditLoggerOptions {
    body: boolean;
    log: Bunyan.Logger;
};

// log all requests.
server.on("after", Restify.auditLogger({
    body: true,
    log: log,
} as IAuditLoggerOptions));
Beispiel #25
0
import * as restify from "restify";
import * as routes from "./routes";

//config
export const server = restify.createServer({
    name: 'myAPI',
    version: '1.0.0'
});

//parsing settings
server.use(restify.acceptParser(server.acceptable));
server.use(restify.queryParser());
server.use(restify.bodyParser());
server.pre(restify.pre.sanitizePath());

//call the routes.ts file for available REST API routes
console.log('setting routes...');
routes.setRoutes(server);

//when running the app will listen locally to port 51234
server.listen(51234, function() {
    console.log('%s listening at %s', server.name, server.url);
})

  if (hapiMiddleware.config.swagger !== undefined) {
    const appRootFromMw = hapiMiddleware.config.swagger.appRoot;
  }

  const pluginAttributes = hapiMiddleware.plugin.register.attributes.name + hapiMiddleware.plugin.register.attributes.version;

  hapiapp.register(hapiMiddleware.plugin, err => {
    if (err) { return console.error("Failed to load plugin:", err); }
    // stat app etc..
  });
});


// Restify Middelware
const app = restify.createServer();
SwaggerNodeRunner.create(config, (err, runner) => {
  if (err) { throw err; }

  const restifyMiddelware = runner.restifyMiddleware();

  restifyMiddelware.register(app);

  const port = process.env.PORT || 10010;
  app.listen(port);
});


const swaggerSecurityHandlerCb = (err: Error) => {
    // do nothing
};
Beispiel #27
0
  /**
   * Initialize the restify server.
   * @override
   * @returns {Promise<void>}
   */
  public initialize() {
    var options = this.options;

    // v1 API 한정
    let serverOptions = options.serverOptions || {};
    serverOptions.formatters = {
      'application/json': (req, res, body, cb) => {
        // Copied from restify/lib/formatters/json.js
        if (body instanceof Error) {
          // snoop for RestError or HttpError, but don't rely on
          // instanceof
        res.statusCode = body.statusCode || 500;
          if (body.body) {
            body = body.body;
            body.stack = body.stack;
            body.extra = body.extra;
          } else {
            body = {
              name: body.name,
              message: body.message,
              stack: body.stack,
              extra: body.extra
            };
          }
        } else if (Buffer.isBuffer(body)) {
          body = body.toString('base64');
        }

        var data = JSON.stringify(body);
        res.setHeader('Content-Length', Buffer.byteLength(data));

        return cb(null, data);
      }
    }
    var server = restify.createServer(serverOptions);

    // Cleans up sloppy URLs on the request object, like /foo////bar/// to /foo/bar.
    // ex) /v2/a/b/ => /v2/a/b
    server.pre(restify.pre.sanitizePath());

    // TODO: 별도의 미들웨어로 분리하자
    // NOTE: /v2/xxx/yyy/:id => /v2/xxx/yyy/:id([a-f\d]{24}) 로 변환
    // :id 는 무조껀 objectid 로 간주함
    server.pre((req, res, next) => {
      if (req.url.indexOf(':id')) {
        req.url = req.url.replace(/:id/g, ':id([a-f\d]{24})');
      }
      next();
    });

    // Set default middleware
    server.use((req, res, next) => {
      debug('\n\n\t\t********** %s %s **********\n', req.method.toUpperCase(), req.url);
      next();
    });
    /*
    restify.CORS.ALLOW_HEADERS.push('Content-Type');
    restify.CORS.ALLOW_HEADERS.push('Authorization');
    restify.CORS.ALLOW_HEADERS.push('X-Requested-With');
    server.use(restify.CORS());
    */
    server.use((req, res, next) => {
      res.header('Access-Control-Allow-Origin', '*');
      res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE,OPTIONS');
      res.header('Access-Control-Allow-Headers', 'X-Requested-With, Content-Type, Authorization, Content-Length');
      next();
    });
    server.use(restify.dateParser());
    server.use(queryParser());
    server.use(restify.bodyParser({
      // TODO: export below params to external configuation file
      maxBodySize: 0
    }));

    if (options.middlewares) {
      server.use(options.middlewares);
    }

    this._adaptee = server;
    return Promise.resolve();
  }
Beispiel #28
0
function startServer(configuration:model.Configuration, database:any) {

    var Q = require('q');

    var restify = require("restify");
    var server = restify.createServer({name: "zander"})
        .pre(restify.pre.sanitizePath())
        .use(restify.fullResponse())
        .use(restify.bodyParser())
        .use(restify.authorizationParser())
        .use(restify.requestLogger())
        .use(restify.queryParser());

    if (configuration.throttle)
        server.use(restify.throttle(configuration.throttle));

    var datas = new data.DataFactory(configuration, database);
    var services = new service.ServiceFactory(datas);
    var controllers = new controller.ControllerFactory(configuration, services);
    var validators = new validate.ValidatorFactory();

    function addController(path:string, controller:any) {

        console.log("Register " + controller.constructor.name + " to path " + path);

        function createControllerRequestHandler(method:(r:model.HttpRequest) => Q.IPromise<model.HttpResponse>) {
            return function (request:any, response:any, next:any) {
                var httpRequest:model.HttpRequest = new model.HttpRequest();
                httpRequest.authorization = request.authorization;
                httpRequest.headers = request.headers;
                httpRequest.parameters = request.params;
                httpRequest.body = request.body;
                httpRequest.log = request.log;
                httpRequest.query = request.query;

                method(httpRequest)
                    .then((httpResponse:model.HttpResponse) => {
                        httpResponse.content !== null
                            ? response.send(httpResponse.statusCode, httpResponse.content)
                            : response.send(httpResponse.statusCode);
                    }, (e) => {
                        request.log.error(e);
                        response.send(500, { "code": "InternalServerError" })
                    });
                return next();
            };
        }

        var httpMethods = ["get", "head", "post", "put", "patch", "del"];

        // For each of these HTTP methods, if the controller has the function with the same name then bind the
        // function and handler so that it will be invoked on such a request on path
        httpMethods
            .filter(function (x:string) {
                return controller[x] !== undefined;
            })
            .forEach(function (x:string) {
                var minAuthLevel = controller[x + "AuthLevel"] || model.AuthenticationLevel.None;
                var validator : string = controller[x + "Validator"];
                var authoriser : string = controller[x + "Authoriser"];
                console.log("Register " + x + " to path " + path + " with min authentication level " + minAuthLevel);

                server[x](path, createControllerRequestHandler((request:model.HttpRequest):Q.IPromise<model.HttpResponse> => {
                    var actualRequest = (request:model.HttpRequest):Q.IPromise<model.HttpResponse> => {
                        if (validator) {
                            var result = validators.get(validator).apply(request);
                            if (!result.success) {
                                return Q(new model.HttpResponse(400, {
                                    "code": "BadRequest",
                                    "message": result.reason
                                }));
                            }
                        }

                        if (!authoriser)
                            return controller[x](request);

                        return services.authorisers.get(authoriser)
                            .authenticate(request.user, request.parameters.target)
                            .then((authorised:service.AuthorisationResult) => {
                                switch (authorised) {
                                    case service.AuthorisationResult.NotFound:
                                        return Q(new model.HttpResponse(404, { "code": "ResourceNotFound", "message": "Resource Not Found" }));

                                    case service.AuthorisationResult.Failure:
                                        return Q(new model.HttpResponse(403, { "code": "Forbidden" }));

                                    case service.AuthorisationResult.Success:
                                        return controller[x](request);
                                }
                            });
                    };
                    return services.authenticate.atLeast(minAuthLevel, request, actualRequest);
                }));
            });
    }

    addController("/verify", controllers.verify);
    addController("/user/", controllers.users);
    addController("/user/:target", controllers.user);
    addController("/project/", controllers.projects);
    addController("/project/:target", controllers.project);

    server.listen(configuration.port);
}
    appId: appId,
    subscriptionKey: subscriptionKey,
    serviceEndpoint: serviceEndpoint
});

// Enum for convenience
// intent names match CafeLUISModel.ts
enum Intents { 
    Book_Table = "Book_Table",
    Greeting = "Greeting",
    None = "None",
    Who_are_you_intent = "Who_are_you_intent"
};

// Create server
let server = restify.createServer();
server.listen(process.env.port || process.env.PORT || 3978, function () {
    console.log(`${server.name} listening to ${server.url}`);
});

// Create adapter
const adapter = new BotFrameworkAdapter( { 
    appId: process.env.MICROSOFT_APP_ID, 
    appPassword: process.env.MICROSOFT_APP_PASSWORD 
});

// Add conversation state middleware
interface CafeBotConvState {
    dialogStack: any[];
    cafeLocation: string;
    dateTime: string;
Beispiel #30
0
 run() {
     const server = restify.createServer();
     server.post('/api/messages', (bot.connector('*') as builder.ChatConnector).listen());
     server.listen(process.env.PORT, () => console.log(`${server.name} listening to ${server.url}`));
 }