当前位置: 首页>>代码示例>>TypeScript>>正文


TypeScript Server.decorate方法代码示例

本文整理汇总了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);
  });
开发者ID:elastic,项目名称:kibana,代码行数:25,代码来源:capabilities_mixin.ts

示例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);
  });
}
开发者ID:elastic,项目名称:kibana,代码行数:35,代码来源:capabilities_mixin.ts

示例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() };
//.........这里部分代码省略.........
开发者ID:,项目名称:,代码行数:101,代码来源:

示例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
开发者ID:AbraaoAlves,项目名称:DefinitelyTyped,代码行数:29,代码来源:decorate.ts

示例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);
开发者ID:AlexGalays,项目名称:DefinitelyTyped,代码行数:30,代码来源:server-decorations.ts

示例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,
//.........这里部分代码省略.........
开发者ID:gingerwizard,项目名称:kibana,代码行数:101,代码来源:space_request_interceptors.test.ts

示例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']
开发者ID:RomkeVdMeulen,项目名称:DefinitelyTyped,代码行数:15,代码来源:server-decorations.ts

示例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);
}
开发者ID:elastic,项目名称:kibana,代码行数:4,代码来源:index.ts

示例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({
//.........这里部分代码省略.........
开发者ID:njd5475,项目名称:kibana,代码行数:101,代码来源:reindex_indices.test.ts


注:本文中的hapi.Server.decorate方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。