当前位置: 首页>>代码示例>>TypeScript>>正文


TypeScript restify.pre类代码示例

本文整理汇总了TypeScript中restify.pre的典型用法代码示例。如果您正苦于以下问题:TypeScript pre类的具体用法?TypeScript pre怎么用?TypeScript pre使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。


在下文中一共展示了pre类的5个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的TypeScript代码示例。

示例1: ShadowsocksManagerService

      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}`);
    });
  });
开发者ID:fang2x,项目名称:outline-server,代码行数:26,代码来源:main.ts

示例2: bootstrap

  public bootstrap(port: number) {
    this.restifyApplication.use(restify.CORS());
    this.restifyApplication.use(restify.pre.sanitizePath());
    this.restifyApplication.use(restify.acceptParser(this.restifyApplication.acceptable));
    this.restifyApplication.use(restify.bodyParser());
    this.restifyApplication.use(restify.queryParser());
    this.restifyApplication.use(restify.authorizationParser());
    this.restifyApplication.use(restify.fullResponse());

    // configure API and error routes
    this.restifyContactRouter.configApiRoutes(this.restifyApplication);
    this.restifyContactRouter.configErrorRoutes(this.restifyApplication);
    // listen on provided ports
    this.restifyApplication.listen(port, () => {
      console.log("%s listening at %s", this.restifyApplication.name, this.restifyApplication.url);
    });
  }
开发者ID:rajajhansi,项目名称:aspnetcore-aurelia-tutorial,代码行数:17,代码来源:restify-application.ts

示例3: initialize

  /**
   * 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();
  }
开发者ID:himulawang,项目名称:island,代码行数:86,代码来源:restify-adapter.ts

示例4: function

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);
})

开发者ID:jeffhollan,项目名称:typescriptRestifyAPI,代码行数:23,代码来源:app.ts

示例5: startServer

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);
//.........这里部分代码省略.........
开发者ID:MorleyDev,项目名称:zander.server,代码行数:101,代码来源:server.ts


注:本文中的restify.pre类示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。