本文整理汇总了TypeScript中hapi.Server.decorate方法的典型用法代码示例。如果您正苦于以下问题:TypeScript Server.decorate方法的具体用法?TypeScript Server.decorate怎么用?TypeScript Server.decorate使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类hapi.Server
的用法示例。
在下文中一共展示了Server.decorate方法的9个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的TypeScript代码示例。
示例1: mergeCapabilities
kbnServer.afterPluginsInit(async () => {
const defaultCapabilities = mergeCapabilities(
...(await Promise.all(
kbnServer.pluginSpecs
.map(spec => spec.getUiCapabilitiesProvider())
.filter(provider => !!provider)
.map(provider => provider(server))
))
);
server.decorate('request', 'getCapabilities', function() {
// Get legacy nav links
const navLinks = server.getUiNavLinks().reduce(
(acc, spec) => ({
...acc,
[spec._id]: true,
}),
{} as Record<string, boolean>
);
return resolveCapabilities(this, modifiers, defaultCapabilities, { navLinks });
});
registerCapabilitiesRoute(server, defaultCapabilities, modifiers);
});
示例2: capabilitiesMixin
export async function capabilitiesMixin(kbnServer: KbnServer, server: Server) {
const modifiers: CapabilitiesModifier[] = [];
server.decorate('server', 'registerCapabilitiesModifier', (provider: CapabilitiesModifier) => {
modifiers.push(provider);
});
// Some plugin capabilities are derived from data provided by other plugins,
// so we need to wait until after all plugins have been init'd to fetch uiCapabilities.
kbnServer.afterPluginsInit(async () => {
const defaultCapabilities = mergeCapabilities(
...(await Promise.all(
kbnServer.pluginSpecs
.map(spec => spec.getUiCapabilitiesProvider())
.filter(provider => !!provider)
.map(provider => provider(server))
))
);
server.decorate('request', 'getCapabilities', function() {
// Get legacy nav links
const navLinks = server.getUiNavLinks().reduce(
(acc, spec) => ({
...acc,
[spec._id]: true,
}),
{} as Record<string, boolean>
);
return resolveCapabilities(this, modifiers, defaultCapabilities, { navLinks });
});
registerCapabilitiesRoute(server, defaultCapabilities, modifiers);
});
}
示例3: async
request = async (
path: string,
spaces: SavedObject[],
setupFn: (server: Server) => null = () => null
) => {
server = new Server();
interface Config {
[key: string]: any;
}
const config: Config = {
'server.basePath': serverBasePath,
'server.defaultRoute': defaultRoute,
};
server.decorate(
'server',
'config',
jest.fn(() => {
return {
get: jest.fn(key => {
return config[key];
}),
};
})
);
server.savedObjects = {
SavedObjectsClient: {
errors: {
isNotFoundError: (e: Error) => e.message === 'space not found',
},
},
getSavedObjectsRepository: jest.fn().mockImplementation(() => {
return {
get: (type: string, id: string) => {
if (type === 'space') {
const space = spaces.find(s => s.id === id);
if (space) {
return space;
}
throw new Error('space not found');
}
},
create: () => null,
};
}),
};
server.plugins = {
spaces: {
spacesClient: {
getScopedClient: jest.fn(),
},
},
xpack_main: {
getFeatures: () =>
[
{
id: 'feature-1',
name: 'feature 1',
app: ['app-1'],
},
{
id: 'feature-2',
name: 'feature 2',
app: ['app-2'],
},
{
id: 'feature-4',
name: 'feature 4',
app: ['app-1', 'app-4'],
},
{
id: 'feature-5',
name: 'feature 4',
app: ['kibana'],
},
] as Feature[],
},
};
let basePath: string | undefined;
server.decorate('request', 'getBasePath', () => basePath);
server.decorate('request', 'setBasePath', (newPath: string) => {
basePath = newPath;
});
// The onRequest interceptor is also included here because the onPostAuth interceptor requires the onRequest
// interceptor to parse out the space id and rewrite the request's URL. Rather than duplicating that logic,
// we are including the already tested interceptor here in the test chain.
initSpacesOnRequestInterceptor(server);
initSpacesOnPostAuthRequestInterceptor(server);
server.route([
{
method: 'GET',
path: '/',
handler: (req: any) => {
return { path: req.path, url: req.url, basePath: req.getBasePath() };
//.........这里部分代码省略.........
示例4: function
// From https://hapijs.com/api/16.1.1#serverdecoratetype-property-method-options
import * as Hapi from 'hapi';
const server = new Hapi.Server();
server.connection({ port: 80 });
const success = function (this: Hapi.ReplyNoContinue) {
return this.response({ status: 'ok' });
};
server.decorate('reply', 'success', success);
declare module 'hapi' {
interface Base_Reply {
success: () => Response;
}
}
server.route({
method: 'GET',
path: '/',
handler: function (request, reply) {
return reply.success();
}
});
// custom typing code for decorating request
示例5: Server
interface HandlerDecorations {
test?: {
test: number;
};
}
}
// 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,
},
asd: 1,
}
});
console.log(server.decorations.toolkit);
示例6: async
request = async (
path: string,
setupFn: (ser: any) => void = () => {
return;
},
testConfig = {}
) => {
server = new Server();
interface Config {
[key: string]: any;
}
const config: Config = {
'server.basePath': '/foo',
...testConfig,
};
server.decorate(
'server',
'config',
jest.fn(() => {
return {
get: jest.fn(key => {
return config[key];
}),
};
})
);
server.savedObjects = {
SavedObjectsClient: {
errors: {
isNotFoundError: (e: Error) => e.message === 'space not found',
},
},
getSavedObjectsRepository: jest.fn().mockImplementation(() => {
return {
get: (type: string, id: string) => {
if (type === 'space') {
if (id === 'not-found') {
throw new Error('space not found');
}
return {
id,
name: 'test space',
};
}
},
create: () => null,
};
}),
};
server.plugins = {
spaces: {
spacesClient: {
getScopedClient: jest.fn(),
},
},
};
initSpacesRequestInterceptors(server);
server.route([
{
method: 'GET',
path: '/',
handler: (req: any) => {
return { path: req.path, url: req.url, basePath: req.getBasePath() };
},
},
{
method: 'GET',
path: '/app/kibana',
handler: (req: any) => {
return { path: req.path, url: req.url, basePath: req.getBasePath() };
},
},
{
method: 'GET',
path: '/api/foo',
handler: (req: any) => {
return { path: req.path, url: req.url, basePath: req.getBasePath() };
},
},
]);
await setupFn(server);
let basePath: string | undefined;
server.decorate('request', 'getBasePath', () => basePath);
server.decorate('request', 'setBasePath', (newPath: string) => {
basePath = newPath;
});
teardowns.push(() => server.stop());
return await server.inject({
method: 'GET',
url: path,
//.........这里部分代码省略.........
示例7: Server
// https://github.com/hapijs/hapi/blob/master/API.md#-serverdecoratetype-property-method-options
import {ResponseToolkit, Server} from "hapi";
const server = new Server({
port: 8000,
});
const success = (h: ResponseToolkit) => {
return h.response({ status: 'ok' });
};
server.start();
server.decorate('toolkit', 'success', success);
console.log(server.decorations.toolkit); // ['success']
示例8: coreMixin
export function coreMixin(kbnServer: KbnServer, server: Server) {
// we suppress type error because hapi expect a function here not an object
server.decorate('server', 'newPlatform', kbnServer.newPlatform as any);
}
示例9: describe
describe('reindex API', () => {
const server = new Server();
server.plugins = {
elasticsearch: {
getCluster: () => ({ callWithRequest: jest.fn() } as any),
} as any,
xpack_main: {
info: {},
},
} as any;
server.config = () => ({ get: () => '' } as any);
server.decorate('request', 'getSavedObjectsClient', () => jest.fn());
const credentialStore = credentialStoreFactory();
const worker = {
includes: jest.fn(),
forceRefresh: jest.fn(),
} as any;
registerReindexIndicesRoutes(server, worker, credentialStore);
beforeEach(() => {
mockReindexService.hasRequiredPrivileges.mockResolvedValue(true);
mockReindexService.detectReindexWarnings.mockReset();
mockReindexService.getIndexGroup.mockReset();
mockReindexService.createReindexOperation.mockReset();
mockReindexService.findAllInProgressOperations.mockReset();
mockReindexService.findReindexOperation.mockReset();
mockReindexService.processNextStep.mockReset();
mockReindexService.resumeReindexOperation.mockReset();
mockReindexService.cancelReindexing.mockReset();
worker.includes.mockReset();
worker.forceRefresh.mockReset();
// Reset the credentialMap
credentialStore.clear();
});
describe('GET /api/upgrade_assistant/reindex/{indexName}', () => {
it('returns the attributes of the reindex operation and reindex warnings', async () => {
mockReindexService.findReindexOperation.mockResolvedValueOnce({
attributes: { indexName: 'wowIndex', status: ReindexStatus.inProgress },
});
mockReindexService.detectReindexWarnings.mockResolvedValueOnce([ReindexWarning.allField]);
const resp = await server.inject({
method: 'GET',
url: `/api/upgrade_assistant/reindex/wowIndex`,
});
// It called into the service correctly
expect(mockReindexService.findReindexOperation).toHaveBeenCalledWith('wowIndex');
expect(mockReindexService.detectReindexWarnings).toHaveBeenCalledWith('wowIndex');
// It returned the right results
expect(resp.statusCode).toEqual(200);
const data = JSON.parse(resp.payload);
expect(data.reindexOp).toEqual({ indexName: 'wowIndex', status: ReindexStatus.inProgress });
expect(data.warnings).toEqual([0]);
});
it("returns null for both if reindex operation doesn't exist and index doesn't exist", async () => {
mockReindexService.findReindexOperation.mockResolvedValueOnce(null);
mockReindexService.detectReindexWarnings.mockResolvedValueOnce(null);
const resp = await server.inject({
method: 'GET',
url: `/api/upgrade_assistant/reindex/anIndex`,
});
expect(resp.statusCode).toEqual(200);
const data = JSON.parse(resp.payload);
expect(data.reindexOp).toBeNull();
expect(data.warnings).toBeNull();
});
it('returns the indexGroup for ML indices', async () => {
mockReindexService.findReindexOperation.mockResolvedValueOnce(null);
mockReindexService.detectReindexWarnings.mockResolvedValueOnce([]);
mockReindexService.getIndexGroup.mockReturnValue(IndexGroup.ml);
const resp = await server.inject({
method: 'GET',
url: `/api/upgrade_assistant/reindex/.ml-state`,
});
expect(resp.statusCode).toEqual(200);
const data = JSON.parse(resp.payload);
expect(data.indexGroup).toEqual(IndexGroup.ml);
});
});
describe('POST /api/upgrade_assistant/reindex/{indexName}', () => {
it('creates a new reindexOp', async () => {
mockReindexService.createReindexOperation.mockResolvedValueOnce({
attributes: { indexName: 'theIndex' },
});
const resp = await server.inject({
//.........这里部分代码省略.........