本文整理匯總了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}`);
});
});
示例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);
});
}
示例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();
}
示例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);
})
示例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);
//.........這裏部分代碼省略.........