本文整理汇总了TypeScript中hapi.Server.ext方法的典型用法代码示例。如果您正苦于以下问题:TypeScript Server.ext方法的具体用法?TypeScript Server.ext怎么用?TypeScript Server.ext使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类hapi.Server
的用法示例。
在下文中一共展示了Server.ext方法的10个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的TypeScript代码示例。
示例1: initAPIAuthorization
export function initAPIAuthorization(server: Server, authorization: AuthorizationService) {
const { actions, checkPrivilegesDynamicallyWithRequest, mode } = authorization;
server.ext('onPostAuth', async (request: Request, h: ResponseToolkit) => {
// if the api doesn't start with "/api/" or we aren't using RBAC for this request, just continue
if (!request.path.startsWith('/api/') || !mode.useRbacForRequest(request)) {
return h.continue;
}
const { tags = [] } = request.route.settings;
const tagPrefix = 'access:';
const actionTags = tags.filter(tag => tag.startsWith(tagPrefix));
// if there are no tags starting with "access:", just continue
if (actionTags.length === 0) {
return h.continue;
}
const apiActions = actionTags.map(tag => actions.api.get(tag.substring(tagPrefix.length)));
const checkPrivileges = checkPrivilegesDynamicallyWithRequest(request);
const checkPrivilegesResponse = await checkPrivileges(apiActions);
// we've actually authorized the request
if (checkPrivilegesResponse.hasAllRequested) {
return h.continue;
}
return Boom.notFound();
});
}
示例2: init
public static init(): Hapi.Server {
const server = new Hapi.Server();
server.connection({
port: 10000,
router: {
isCaseSensitive: false,
stripTrailingSlash: true
},
routes: {
timeout: {
server: 10000,
socket: false
},
cors: {
credentials: true,
origin: ['*'],
headers: ['Accept', 'Authorization',
'Content-Type', 'If-None-Match',
'Access-Control-Allow-Origin',
'Accept-Language']
},
files: {
relativeTo: Path.join(__dirname, '../')
}
}
});
server.ext('onPreResponse', corsHeaders);
server.register(Inert, () => {});
Api.init(server);
return server;
}
示例3: initSpacesOnRequestInterceptor
export function initSpacesOnRequestInterceptor(server: Server) {
const serverBasePath: string = server.config().get('server.basePath');
server.ext('onRequest', async function spacesOnRequestHandler(request: any, h: any) {
const path = request.path;
// If navigating within the context of a space, then we store the Space's URL Context on the request,
// and rewrite the request to not include the space identifier in the URL.
const spaceId = getSpaceIdFromPath(path, serverBasePath);
if (spaceId !== DEFAULT_SPACE_ID) {
const reqBasePath = `/s/${spaceId}`;
request.setBasePath(reqBasePath);
const newLocation = path.substr(reqBasePath.length) || '/';
const newUrl = {
...request.url,
path: newLocation,
pathname: newLocation,
href: newLocation,
};
request.setUrl(newUrl);
}
return h.continue;
});
}
示例4: start
public async start(config: HttpConfig) {
this.log.debug('starting http --> https redirect server');
if (!config.ssl.enabled || config.ssl.redirectHttpFromPort === undefined) {
throw new Error(
'Redirect server cannot be started when [ssl.enabled] is set to `false`' +
' or [ssl.redirectHttpFromPort] is not specified.'
);
}
// Redirect server is configured in the same way as any other HTTP server
// within the platform with the only exception that it should always be a
// plain HTTP server, so we just ignore `tls` part of options.
this.server = createServer({
...getServerOptions(config, { configureTLS: false }),
port: config.ssl.redirectHttpFromPort,
});
this.server.ext('onRequest', (request: Request, responseToolkit: ResponseToolkit) => {
return responseToolkit
.redirect(
formatUrl({
hostname: config.host,
pathname: request.url.pathname,
port: config.port,
protocol: 'https',
search: request.url.search,
})
)
.takeover();
});
try {
await this.server.start();
this.log.debug(`http --> https redirect server running at ${this.server.info.uri}`);
} catch (err) {
if (err.code === 'EADDRINUSE') {
throw new Error(
'The redirect server failed to start up because port ' +
`${config.ssl.redirectHttpFromPort} is already in use. Ensure the port specified ` +
'in `server.ssl.redirectHttpFromPort` is available.'
);
} else {
throw err;
}
}
}
示例5: function
server.register(hapiAuthJwt2, err => {
if (err){
console.error(err);
throw err;
}
server.auth.strategy('jwt', 'jwt', false, {
key: config.auth.jwtSecret,
validateFunc: (decoded, request, callback) => {
database.instance['app_user'].findDoc({ email: decoded.email }, function(err, doc){
if (err || !doc || !doc.length)
return callback(err, false);
return callback(null, true, { email: doc[0].email });
});
}, verifyOptions: {
issuer: config.auth.jwtOptions.issuer,
audience: config.auth.jwtOptions.audience
}
});
server.auth.default('jwt');
server.ext('onPreResponse', function(req, rep){
// resend a token on every response to update token expiration
if (!req.auth.isAuthenticated)
return rep.continue();
var payload = {
email: req.auth.credentials.email
};
var token = jwt.sign(payload, config.auth.jwtSecret, {
expiresIn: '3h',
audience: 'audience',
issuer: 'issuer'
});
Object.assign(req.response.source, { token });
return rep.continue();
});
});
示例6: async
getServerLibs: async () => {
if (!serverLibs) {
const server = new Hapi.Server({ port: 111111 });
const versionHeader = 'kbn-version';
const xsrfHeader = 'kbn-xsrf';
server.ext('onPostAuth', (req: any, h: any) => {
const isSafeMethod = req.method === 'get' || req.method === 'head';
const hasVersionHeader = versionHeader in req.headers;
const hasXsrfHeader = xsrfHeader in req.headers;
if (!isSafeMethod && !hasVersionHeader && !hasXsrfHeader) {
throw badRequest(`Request must contain a ${xsrfHeader} header.`);
}
return h.continue;
});
serverLibs = compose(server);
initManagementServer(serverLibs);
}
return serverLibs;
},
示例7: function
// From https://hapijs.com/api/16.1.1#requestsetmethodmethod
import * as Hapi from 'hapi';
const server = new Hapi.Server();
server.connection({ port: 80 });
const onRequest: Hapi.ServerExtRequestHandler = function (request, reply) {
// Change all requests to 'GET'
request.setMethod('GET');
return reply.continue();
};
server.ext('onRequest', onRequest);
示例8: Server
});
/*
* Request events
*/
const hash = Crypto.createHash('sha1');
request.events.on("peek", (chunk) => {
hash.update(chunk);
});
request.events.once("finish", () => {
console.log(hash.digest('hex'));
});
request.events.once("disconnect", () => {
console.error('request aborted');
});
return h.continue;
};
const server = new Server(options);
server.route(serverRoute);
server.ext('onRequest', onRequest, {
before: 'test',
});
server.start();
console.log('Server started at: ' + server.info.uri);
示例9: require
// production
envVariables = require('./../../env.json');
}
// set up server
var server = new Hapi.Server();
server.connection({port: 3001, labels: 'api'});
server.connection({port: 3002, labels: 'realtime'});
// Add ability to reply errors with data
server.ext('onPreResponse', (request, reply:any) => {
var response:any = request.response;
if (!response.isBoom) {
return reply.continue();
}
if (response.data) {
response.output.payload.data = response.data;
}
return reply(response);
});
// Register plugins
server.register([
/* {
register: require('chairo'),
options: {
log: 'silent'
}
},*/ // wait for support of hapi 9.x.x
{
register: require('inert')
示例10: 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 } }
});
};