本文整理匯總了TypeScript中@hapi/hapi.Server.route方法的典型用法代碼示例。如果您正苦於以下問題:TypeScript Server.route方法的具體用法?TypeScript Server.route怎麽用?TypeScript Server.route使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類@hapi/hapi.Server
的用法示例。
在下文中一共展示了Server.route方法的10個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的TypeScript代碼示例。
示例1:
server.register(Basic).then(() => {
server.auth.strategy('simple', 'basic', { validate });
server.auth.default('simple');
server.route({ method: 'GET', path: '/', options: { auth: 'simple' } });
});
示例2: async
server.register([Basic, Nes]).then(() => {
// Set up HTTP Basic authentication
interface User {
username: string;
password: string;
name: string;
id: string;
}
const users: { [index: string]: User } = {
john: {
username: 'john',
password: '$2a$10$iqJSHD.BGr0E2IxQwYgJmeP3NvhPrXAeLSaGCj6IR/XU5QtjVu5Tm', // 'secret'
name: 'John Doe',
id: '2133d32a'
}
};
const validate: Basic.Validate = async (request, username, password, h) => {
const user = users[username];
if (!user) {
return { credentials: null, isValid: false };
}
let isValid = await Bcrypt.compare(password, user.password)
return { isValid, credentials: { id: user.id, name: user.name } };
};
server.auth.strategy('simple', 'basic', {validateFunc: validate});
server.auth.default('simple');
// Configure route with authentication
server.route({
method: 'GET',
path: '/h',
options: {
id: 'hello',
handler: function (request: Request, h: ResponseToolkit) {
return 'Hello ' + request.auth.credentials.name;
}
}
});
return server.start();
});
示例3:
server.register(Nes).then(() => {
server.route({
method: 'GET',
path: '/h',
options: {
id: 'hello',
handler: (request: Request, h: ResponseToolkit) => {
return 'world!';
}
}
});
return server.start();
});
示例4: Server
(async () => {
const server = new Server({ debug: false, port: 0 });
server.register({
plugin: hapiswagger,
options: {
cors: true,
jsonPath: '/jsonpath',
info: {
title: 'a',
description: 'b',
termsOfService: 'c',
contact: {
name: 'a',
url: 'localhost',
email: 'who@where.com'
}
},
tagsGroupFilter: (tag: string) => tag !== 'api'
}
});
server.route({
method: 'GET',
path: '/',
handler: () => 'hi',
options: {
auth: false,
plugins: {
'hapi-swagger': {
order: 2,
deprecated: false,
'x-api-stuff': 'a'
}
}
}
});
await server.start();
await server.stop();
})();
示例5: async
const provision = async () => {
await server.register(inert);
await server.register({
plugin: inert,
options: { etagsCacheMaxSize: 400 },
});
await server.register({
plugin: inert,
once: true,
});
server.route({
method: 'GET',
path: '/{param*}',
handler: {
directory: {
path: '.',
redirectToSlash: true,
index: true
}
}
});
// https://github.com/hapijs/inert#serving-a-single-file
server.route({
method: 'GET',
path: '/{path*}',
handler: {
file: 'page.html'
}
});
// https://github.com/hapijs/inert#customized-file-response
server.route({
method: 'GET',
path: '/file',
handler(request, reply) {
let path = 'plain.txt';
if (request.headers['x-magic'] === 'sekret') {
path = 'awesome.png';
}
return reply.file(path).vary('x-magic');
}
});
const handler: Lifecycle.Method = (request, h) => {
const response = request.response;
if (response instanceof Error && response.output.statusCode === 404) {
return h.file('404.html').code(404);
}
return h.continue;
};
server.ext('onPostHandler', handler);
const file: inert.FileHandlerRouteObject = {
path: '',
confine: true,
};
const directory: inert.DirectoryHandlerRouteObject = {
path: '',
listing: true
};
server.route({
path: '',
method: 'GET',
handler: {
file,
directory: {
path() {
if (Math.random() > 0.5) {
return '';
} else if (Math.random() > 0) {
return [''];
}
return new Error('');
}
},
},
options: { files: { relativeTo: __dirname } }
});
};
示例6: async
const provision = async () => {
await server.register({
plugin: Vision,
options: {
engines: { hbs: Handlebars },
path: __dirname + '/templates',
}
});
server.views({
engines: { hbs: Handlebars },
path: __dirname + '/templates',
});
const context = {
title: 'Views Example',
message: 'Hello, World',
};
console.log(await server.render('hello', context));
server.route({
method: 'GET',
path: '/view',
handler: async (request: Request, h: ResponseToolkit) => {
return request.render('test', { message: 'hello' });
},
});
server.route({
method: 'GET',
path: '/',
handler: {
view: {
template: 'hello',
context: {
title: 'Views Example',
message: 'Hello, World',
},
},
},
});
const handler = (request: Request, h: ResponseToolkit) => {
const context = {
title: 'Views Example',
message: 'Hello, World',
};
return h.view('hello', context);
};
server.route({ method: 'GET', path: '/', handler });
server.route({
method: 'GET',
path: '/temp1',
handler: {
view: {
template: 'temp1',
options: {
compileOptions: {
noEscape: true,
},
},
},
},
});
};
示例7: Server
// Example 1
// http://localhost:8000/album-name/song-optional
const getAlbum: Lifecycle.Method = (request, h) => {
console.log(request.params);
return 'ok: ' + request.path;
};
const serverRoute1: ServerRoute = {
path: '/{album}/{song?}',
method: 'GET',
handler: getAlbum
};
// Example 2
// http://localhost:8000/person/rafael/fijalkowski
const getPerson: Lifecycle.Method = (request, h) => {
const nameParts = request.params.name.split('/');
return { first: nameParts[0], last: nameParts[1] };
};
const serverRoute2: ServerRoute = {
path: '/person/{name*2}',
method: 'GET',
handler: getPerson
};
const server = new Server(options);
server.route(serverRoute1);
server.route(serverRoute2);
server.start();
console.log('Server started at: ' + server.info.uri);
示例8: authenticate
const scheme: ServerAuthScheme = (server, options) => {
return {
authenticate(request, h) {
const req = request.raw.req;
const authorization = req.headers.authorization;
if (!authorization) {
throw Boom.unauthorized(null, 'Custom');
}
return h.authenticated({ credentials: { name: 'john', } });
}
};
};
server.auth.scheme('custom', scheme);
server.auth.strategy('default', 'custom');
server.route({
method: 'GET',
path: '/',
handler: async (request: Request, h: ResponseToolkit) => {
try {
const { credentials } = await request.server.auth.test('default', request);
return { status: true, user: credentials.name };
} catch (err) {
return { status: false };
}
}
});
server.start();
示例9: Server
// Test basic types.
const server = new Server({
port: 8000,
});
server.start();
server.decorate('toolkit', 'success', function() {
return this.response({ status: 'ok' });
});
server.decorate('handler', 'test', (route, options) => (req, h) => 123);
server.route({
method: 'GET',
path: '/',
handler: {
test: {
test: 123,
}
}
});
console.log(server.decorations.toolkit);
// Test decorators with additional arguments
declare module '@hapi/hapi' {
interface Server {
withParams(x: number, y: string): string;
}
interface ResponseToolkit {
示例10: handler
// https://github.com/hapijs/hapi/blob/master/API.md#errors
import { Request, ResponseToolkit, Server, ServerOptions, ServerRoute } from "@hapi/hapi";
import * as Boom from "boom";
const options: ServerOptions = {
port: 8000,
};
const serverRoutes: ServerRoute[] = [
{
path: '/badRequest',
method: 'GET',
handler(request, h) {
throw Boom.badRequest('Unsupported parameter');
}
},
{
path: '/internal',
method: 'GET',
handler(request, h) {
throw new Error('unexpect error');
}
},
];
const server = new Server(options);
server.route(serverRoutes);
server.start();
console.log('Server started at: ' + server.info.uri);