本文整理汇总了TypeScript中hapi.Server.route方法的典型用法代码示例。如果您正苦于以下问题:TypeScript Server.route方法的具体用法?TypeScript Server.route怎么用?TypeScript Server.route使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类hapi.Server
的用法示例。
在下文中一共展示了Server.route方法的10个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的TypeScript代码示例。
示例1: require
server.register(Vision, (err) => {
if (err) {
throw err;
}
server.views({
engines: { html: require('handlebars') },
path: __dirname + '/templates'
});
const context = {
title: 'Views Example',
message: 'Hello, World'
};
server.render('hello', context, {}, (err, rendered, config) => {
console.log(rendered);
});
// https://github.com/hapijs/vision/blob/master/API.md#requestrendertemplate-context-options-callback
server.views({
engines: { html: require('handlebars') },
path: __dirname + '/templates'
});
server.route({
method: 'GET',
path: '/view',
handler: function (request, reply) {
request.render('test', { message: 'hello' }, {}, (err, rendered, config) => {
return reply(rendered);
});
}
});
// https://github.com/hapijs/vision/blob/master/API.md#the-view-handler
server.views({
engines: { html: require('handlebars') },
path: __dirname + '/templates'
});
server.route({
method: 'GET',
path: '/',
handler: {
view: {
template: 'hello',
context: {
title: 'Views Example',
message: 'Hello, World'
}
}
}
});
// https://github.com/hapijs/vision/blob/master/API.md#replyviewtemplate-context-options
server.views({
engines: { html: require('handlebars') },
path: __dirname + '/templates'
});
const handler: Hapi.RouteHandler = function (request, reply) {
const context = {
title: 'Views Example',
message: 'Hello, World'
};
return reply.view('hello', context);
};
server.route({ method: 'GET', path: '/', handler: handler });
});
示例2: function
export default function(): void {
logInfo(`(cluster: ${cluster.worker.id}) Initializing server`);
const server = new hapi.Server();
server.connection({ port: config.port.http });
// '/' for signation
server.route({
method: 'get',
path: '/',
handler: (_, reply) => reply().code(204)
})
// REST endpoints routing
httpEndpoints.forEach(endpoint => {
if (endpoint.name === 'album/files/upload') {
server.route({
method: 'post',
path: `/${endpoint.name}`,
config: {
payload: {
output: 'file',
parse: true,
maxBytes: dataSize.fromMiB(100),
allow: 'multipart/form-data'
},
handler: (request: any, reply: any): void => {
apiHandler(endpoint, request, reply);
}
}
});
} else {
server.route({
method: 'post',
path: `/${endpoint.name}`,
handler: (request: any, reply: any): void => {
apiHandler(endpoint, request, reply);
}
});
}
});
// Stream endpoints routing
server.register(hapiws, (err) => {
streamEndpoints.forEach(name => {
server.route({
method: 'post',
path: `/streams/${name}`,
config: {
plugins: {
websocket: {
only: true,
connect: (options) => {
streamHandler(name, options['ws'], options['req']);
}
}
}
},
handler: (req, reply) => { return; }
});
});
});
server.route({ method: '*', path: '/{p*}', handler: notFoundHandler });
server.start(() => {
logInfo(`(cluster: ${cluster.worker.id}) Listening at ${server.info.uri}`);
});
}
示例3: start
async function start() {
await server.register({
plugin: good,
options: {
ops: {
interval: 1000
},
reporters: {
logs: [
{
module: 'good-squeeze',
name: 'Squeeze',
args: [
{
log: '*',
response: {
include: 'api',
exclude: 'health'
}
}
]
},
{
module: 'good-console'
},
'stdout'
],
errors: [
{
module: 'good-squeeze',
name: 'Squeeze',
args: [{error: '*'}]
},
{
module: 'good-console'
},
'stderr'
]
}
}
});
server.route({
method: 'GET',
path: '/',
options: {
description: 'Basic default route that returns a JSON object',
tags: ['api'],
handler: () => ({
host: os.hostname(),
at: new Date().toUTCString()
})
}
});
server.route({
method: 'GET',
path: '/details',
options: {
description: 'Details route that returns details of the host',
tags: ['api'],
handler: () => ({
hostname: os.hostname(),
arch: os.arch(),
platfoirm: os.platform(),
cpus: os.cpus().length,
totalmem: humanize.filesize(os.totalmem()),
networkInterfaces: os.networkInterfaces()
})
}
});
server.route({
method: 'GET',
path: '/status/{code}',
options: {
description: 'Route which echos back the status code as an error object',
tags: ['api'],
validate: {
params: {
code: Joi.number()
.integer()
.positive()
.required()
.allow(allStatusCodes)
}
},
handler: (req: Hapi.Request, h: Hapi.ResponseToolkit) => {
const statusCode = parseInt(req.params.code);
if (statusCode >= 400) {
return Boom.boomify(new Error(`Forced status code: ${statusCode}`), {
statusCode
});
}
return h
.response({statusCode, message: httpStatus.getStatusText(statusCode)})
.code(statusCode);
}
}
//.........这里部分代码省略.........
示例4: Server
import { Server } from "hapi";
const server = new Server();
server.route({
method: 'get',
path: "/test",
options: {
ext: {
onPreResponse: {
method(_request, h) {
return h.continue;
},
},
onPostHandler: [{
method(_request, h) {
return h.continue;
},
}],
}
}
});
示例5:
/// <reference path="./typings/index.d.ts" />
"use strict";
import * as hapi from "hapi";
const server: hapi.Server = new hapi.Server()
server.connection({ port: 3000 });
server.route({
method: "GET",
path: "/",
handler: (request: hapi.Request, reply: hapi.IReply) => {
reply("Hello World")
}
});
server.start((err) => {
if (err) {
throw err;
}
console.log("server running at 3000");
})
示例6: function
method: ['OPTIONS', '*']
};
// different handlers
var routeConfig: Hapi.RouteConfiguration = {
path: '/signin',
method: 'PUT',
handler: 'some registered handler'
};
var routeConfig: Hapi.RouteConfiguration = {
path: '/signin',
method: 'PUT',
handler: function (request, reply) {
return reply('ok');
}
};
const server = new Hapi.Server();
server.route(routeConfig);
// Handler in config
const user: Hapi.RouteAdditionalConfigurationOptions = {
cache: { expiresIn: 5000 },
handler: function (request, reply) {
return reply({ name: 'John' });
}
};
server.route({method: 'GET', path: '/user', config: user });
示例7: Server
// https://github.com/hapijs/hapi/blob/master/API.md#-servertablehost
import {Request, ResponseToolkit, Server, ServerOptions} from "hapi";
const options: ServerOptions = {
port: 8000,
};
const server = new Server(options);
server.app.key = 'value2';
server.route({
path: '/',
method: 'GET',
handler: (request: Request, h: ResponseToolkit) => {
return h.response("Hello World");
}
});
server.start();
const table = server.table();
console.log(table);
console.log('Server started at: ' + server.info.uri);
示例8: function
server.handler('test', handler);
interface TestPluginConfig {
msg: string;
}
declare module 'hapi' {
interface RouteHandlerPlugins {
test?: TestPluginConfig;
}
}
server.route({
method: 'GET',
path: '/',
handler: { test: { msg: 'test' } }
});
server.start(function (err) { });
// example 2
handler = function (route, options: TestPluginConfig) {
return function (request, reply) {
return reply('new handler: ' + options.msg);
}
};
示例9: new
static Start<T extends IStartup>(startup: { new (): T; }, options: StartOptions) {
//static Start<T extends IStartup>(options: StartOptions) {
//var t = new T();
var start = new startup();
console.log('START CONFIGURATION: ' + start);
var appBuilder = new AppBuilder();
start.Configuration(appBuilder);
const server = new Hapi.Server();
server.connection(
{
port: options.port,
routes: { cors: options.cors}
}
);
console.log('Count of controllers: ' + appBuilder.controllers.count());
appBuilder.controllers.getItems().forEach(function(type) {
console.log('Controller Type: ' + type);
var controllerInstance = new type();
console.log('Controller Instance: ' + controllerInstance);
var routePrefix = Reflect.getMetadata("RoutePrefix", controllerInstance.constructor);
console.log('routePrefix: ' + routePrefix);
var methods = WebApp.getMethods(controllerInstance.constructor);
var methodNames = Object.getOwnPropertyNames(type.prototype).filter(function(p) {
if (p == 'constructor') {
return false;
}
return typeof type.prototype[p] === 'function';
})
console.log('methodNames:');
console.log(methodNames);
methodNames.forEach(function(name) {
//console.log(controllerInstance[name]);
//console.log(Object.getOwnPropertyDescriptor(type, name));
//console.log(Object.getOwnPropertyDescriptor(type.prototype, name));
//console.log(Object.getOwnPropertyDescriptor(controllerInstance, name));
var methodDescriptor = Object.getOwnPropertyDescriptor(type.prototype, name);
var metaMethod = Reflect.getMetadata('Method', methodDescriptor.value);
var metaRoute = Reflect.getMetadata('Route', methodDescriptor.value);
console.log('Method: ' + metaMethod);
console.log('Route: ' + metaRoute);
//var metaMethod = Reflect.getMetadata("Method", methodDescriptor.value);
//var metaRoute = Reflect.getMetadata("Route", methodDescriptor.value);
//console.log('Method:' + metaMethod);
//console.log('Route:' + metaRoute);
// TODO: Do a safe route building here, supporting prefix with and without trailing /.
var safeRoute = '/' + routePrefix + '/' + metaRoute;
console.log('Safe Route: ' + safeRoute);
var handler = new RequestHandler(type, name);
server.route({
method: metaMethod,
path: safeRoute,
config: {
tags: ['api'],
description: '[Should be read from decoration on API method]'
},
handler: function(request, reply) {
// IMPORTANT: We can't bind the process method directly to the handler property, that will invalidate .this within the handler.
handler.process(request, reply);
}
});
});
});
var modules = WebApp.activeModules(appBuilder);
modules.getItems().forEach(function(module) {
server.register({
register: module.type,
options: module.options
}, (err) => {
if (err) {
console.error('Failed to load plugin:', err);
}
});
});
if (appBuilder.configuration.properties["directory:browser"] === true) {
let browserPath = appBuilder.configuration.properties["directory:path"];
//.........这里部分代码省略.........
示例10:
register: (server:Server, options:ServerRegisterOptions) => {
// Assuming the Inert plugin was registered previously
server.path(__dirname + '../static');
server.route(serverRouteOption);
}