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


TypeScript koa.use函数代码示例

本文整理汇总了TypeScript中koa.use函数的典型用法代码示例。如果您正苦于以下问题:TypeScript use函数的具体用法?TypeScript use怎么用?TypeScript use使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。


在下文中一共展示了use函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的TypeScript代码示例。

示例1: it

it('should reject invalid data and stop request cycle', async done => {
  expect.assertions(2);
  const app = new Koa();
  const data = {
    id: 1,
    name: 'John Smith',
    comment: 'A long comment about this generic person',
  };

  // Add middlewares
  app.use((ctx, next) => {
    (ctx.request as any).body = data; // Hack to inject a body
    return next();
  });
  app.use(ensureSchema(exampleSchema));
  app.use(ctx => fail('should not continue requests'));

  const response = await request(app.callback()).get('/');

  // Assertions
  expect(response.status).toBe(500);
  expect(response.text).toEqual('Internal Server Error');

  // Done
  done();
});
开发者ID:komapijs,项目名称:komapi,代码行数:26,代码来源:ensureSchema.ts

示例2: it

it('should log latency in milliseconds', async done => {
  expect.assertions(3);
  const app = new Koa();
  const spy = jest.fn();

  // Add middlewares
  app.use((ctx, next) => {
    // Add mock data
    ctx.request.startAt = Date.now();
    ctx.request.log = { info: spy } as any;
    return next();
  });
  app.use(requestLogger());
  app.use((ctx, next) => new Promise(resolve => setTimeout(resolve, 125)).then(next));

  const response = await request(app.callback()).get('/');

  // Assertions
  expect(spy).toHaveBeenCalledTimes(1);
  expect(spy.mock.calls[0][0].latency).toBeGreaterThan(120);
  expect(spy.mock.calls[0][0].latency).toBeLessThan(1200);

  // Done
  done();
});
开发者ID:komapijs,项目名称:komapi,代码行数:25,代码来源:requestLogger.ts

示例3: it

    it('works', function(done){

        let app = new Koa();
        app.use(k(r.get('/hello', hello)));
        app.use(k(r.get('/bye', bye)));

        let request = Request.agent(listen(app));

        // request.get('/else')
        // .expect(404)        
        // .end(error=>{
        //     if(error) throw error;            
        // })

        // request.get('/hello')
        // .expect(200)
        // .expect('hello')
        // .end(error=>{
        //     if(error) throw error;
        // });

        request.get('/bye')
        .expect(200)
        .expect('bye')
        .end((error, response) =>{                  
            if(error) throw error;
            done();
        })
    })
开发者ID:D10221,项目名称:kua,代码行数:29,代码来源:route_test.ts

示例4: it

it('should hide "additionalDevelopmentData" in production', async done => {
  expect.assertions(2);
  const app = new Koa();
  app.env = 'production';

  // Add middlewares
  app.use(errorHandler());
  app.use(ctx => {
    throw new Error('A custom error');
  });

  const response = await request(app.callback()).get('/');

  // Assertions
  expect(response.status).toBe(500);
  expect(response.body).toEqual({
    error: {
      code: '',
      error: 'Internal Server Error',
      message: 'An internal server error occurred',
      status: 500,
    },
  });

  // Done
  done();
});
开发者ID:komapijs,项目名称:komapi,代码行数:27,代码来源:errorHandler.ts

示例5:

	public async register<T>(endPoint: EndPoint): Promise<void> {

		// routes
		const router = endPoint.getRouter();
		if (router) {
			this.app.use(router.getRouter().routes());
			this.app.use(router.getRouter().allowedMethods());

			// pretty print registered paths with methods
			const methods: Map<string, string[]> = new Map<string, string[]>();
			router.getRouter().stack.forEach(layer => methods.set(layer.path, [ ...methods.get(layer.path) || [], ...layer.methods ]));
			uniq(router.getRouter().stack.map(layer => layer.path)).sort().forEach(path => {
				logger.info(null, '  %s (%s)', path, methods.get(path).join(','));
			});
		}

		// register model and serializer
		endPoint
			.registerModel()
			.registerSerializer();

		// import data
		await endPoint.import();

		// invalidate VP cache
		await apiCache.invalidateVp();
	}
开发者ID:freezy,项目名称:node-vpdb,代码行数:27,代码来源:server.ts

示例6: beforeAll

    beforeAll((done)=> {
        jasmine.DEFAULT_TIMEOUT_INTERVAL=1000;
        const Koa = require('koa');

        const busboy = new KoaBusBoy({
            limits: {
                fields: 1,
                fileSize: 1
            }
        });

        const app = new Koa();

        app.use(busboy);

        app.use((ctx: any)=> {
            if (ctx.formData) {
                ctx.body = ctx.formData;
            } else {
                ctx.body = 'hello world';
            }
        });

        app.on('error', (error: Error, ctx: any)=> {
            ctx.status = 400;
            ctx.body = error.message;
        });
        app.listen(3001, ()=> {
            done();
        });
    });
开发者ID:sqram,项目名称:koa-async-body,代码行数:31,代码来源:limit.spec.ts

示例7: it

    it('200', async (done) => {

        let app = new Koa();
        //No Auth , no restriction 
        app.use(dmz)
        
        //@restrict('admin')    
        const restricted = router.get('/users/:name*', async function (name, next: KoaNext) {
            this.body = 'ok';
        });
        const a = new Auth(getUser);        
        app.use(a.requireAuth(restricted));

        // restrict user exists is users, sets ctx.user        
        // app.use(auth(findUser));
        // restrict user in 'role'
        app.use(access);
        
        //Auth but no restriction
        app.use(unrestricted);
        request(listen(app))
            .get('/users/bob')
            .set('Authentication', authorize('admin:admin'))
            .expect(200)
            .end((error, r) => {
                if (error) throw error;
                done()
            });
    });
开发者ID:D10221,项目名称:koa-tiny-acl,代码行数:29,代码来源:tests.ts

示例8: test

test('secret:200', { skip: true }, async (t) => {

    let store = await getStore(false);
    let app = new Koa()
    //Auth   
    app.use(auth(users.service.fromCredentials));
    //Secured
    app.use(router.get('/secret',
        async function (args, next) {
            let ctx: Koa.Context = this;
            await delay(5);
            ctx.body = "ok";
            //ctx.status = 200;
        }));

    let request = supertest.agent(listen(app));
    let a = `Basic ${new Buffer('admin:admin').toString('Base64')}`;
    request.get('/secret')
        .set('Authentication', a)
        .expect(200).end(async (err, res) => {
            await delay(5);
            t.assert(!err);
            if (err) debug(`Agent: Error: ${err.message}`);
            t.end();
        });
});
开发者ID:D10221,项目名称:koapp,代码行数:26,代码来源:routes_auth_test.ts

示例9: constructor

	constructor() {
		this.app = new Application();
		this.app.use(koaLogger());
		this.app.use(koaResponseTime());
		this.app.use(koaBodyParser({ onerror: handleParseError }));
		this.app.use(koaErrorHandler());
		this.app.use(koaRestHandler());
		this.app.use(koaAuth());
		this.app.use(koaCors({ exposeHeaders, allowHeaders, origin, maxAge: 600, credentials: true, keepHeadersOnError: true }));
		this.app.use(koaJson({ pretty: false, param: 'pretty' }));
		this.app.use(apiCache.middleware.bind(apiCache));

		/* istanbul ignore next: host website at the same time, currently used for website CI */
		if (process.env.WEBAPP) {
			const webappPath = resolve(__dirname, process.env.WEBAPP);
			if (existsSync(webappPath)) {
				logger.warn(null, '[Server] Statically hosting website at %s', webappPath);
				this.app.use(koaWebsiteHandler(webappPath));
			} else {
				logger.warn(null, '[Server] Fix env WEBAPP, nothing found at %s (%s)', webappPath, process.env.WEBAPP);
			}
		}

		/* istanbul ignore if */
		if (process.env.ELASTIC_APM_ENABLED) {
			logger.info(null, '[Server] Elastic application performance monitoring at %s enabled.', process.env.ELASTIC_APM_SERVER_URL);
			this.setupApmFilter();
		}
	}
开发者ID:freezy,项目名称:node-vpdb,代码行数:29,代码来源:server.ts

示例10: createHttpServer

export function createHttpServer(): HttpServer {
  const koa = new Koa()
  installMiddlewares(koa)
  const router = new KoaRouter()
  koa.use(router.routes())
  koa.use(router.allowedMethods())
  return httpCreateServer(koa.callback())
}
开发者ID:ohjames,项目名称:blaggart,代码行数:8,代码来源:index.ts

示例11: it

it('should set requestId automatically and capture custom properties', async done => {
  expect.assertions(3);
  const app = new Koa();
  const ns = cls.createNamespace('my-namespace');

  // Add middlewares
  app.use((ctx, next) => {
    // Add mock data
    ctx.request.requestId = ctx.request.headers['x-request-id'];
    return next();
  });
  app.use(setTransactionContext(ns));
  app.use((ctx, next) => {
    ns.set('delay', ctx.request.headers['x-delay']);
    return next();
  });
  app.use(async ctx => {
    await new Promise(resolve => setTimeout(resolve, parseInt(ctx.request.headers['x-delay'], 10)));
    ctx.body = {
      requestId: ns.get('requestId'),
      delay: ns.get('delay'),
    };
  });

  const server = request(app.callback());
  const responses = await Promise.all([
    server
      .get('/')
      .set('x-request-id', '1')
      .set('x-delay', '100'),
    server
      .get('/')
      .set('x-request-id', '2')
      .set('x-delay', '1'),
    server
      .get('/')
      .set('x-request-id', '3')
      .set('x-delay', '50'),
  ]);

  // Assertions
  expect(responses[0].body).toEqual({
    requestId: '1',
    delay: '100',
  });
  expect(responses[1].body).toEqual({
    requestId: '2',
    delay: '1',
  });
  expect(responses[2].body).toEqual({
    requestId: '3',
    delay: '50',
  });

  // Done
  done();
});
开发者ID:komapijs,项目名称:komapi,代码行数:57,代码来源:setTransactionContext.ts

示例12: frameguardTest

/**
 * @summary Test for {@see helmet#frameguard} function.
 */
function frameguardTest() {
    app.use(helmet.frameguard());
    app.use(helmet.frameguard({}));
    app.use(helmet.frameguard({ action: 'deny' }));
    app.use(helmet.frameguard({ action: 'sameorigin' }));
    app.use(helmet.frameguard({
      action: 'allow-from',
      domain: 'http://example.com'
    }));
}
开发者ID:AbraaoAlves,项目名称:DefinitelyTyped,代码行数:13,代码来源:koa-helmet-tests.ts

示例13: it

    it('goes', (done) => {
                                 
        const auth = kua.create(
            kua.basicAuth(testing.store.find),
            kua.acl<User, string>(ctx => ctx.user, user => user.roles) 
             )

        const app = new Koa();
        app.use(router.get('/bye', bye));
        app.use(router.get('/hello', hello));
        app.use(auth.lock(router.get('/admin', admin), ['admin']));

        let request = Request(listen(app));

        request.get('/hello')
            .expect('hello')
            .end((error) => {
                if (error) throw error;
            })

        request.get('/admin')
            .set(auth.provider.key, auth.provider.encode({ name: 'admin', password: 'admin' }))
            .expect('admin')
            .end((error) => {
                if (error) throw error;
            })

        request.get('/admin')
            //.set('Authentication', JSON.stringify({ name: 'admin', password: 'admin' }))
            .expect(407) //Auth Required
            .end((error) => {
                if (error) throw error;
            })

        request.get('/admin')
            .set(auth.provider.key, auth.provider.encode({ name: 'admin', password: 'xxx' }))
            .expect(401) //UnAuthorized : bad credentials 
            .end((error) => {
                if (error) throw error;
            })

        request.get('/admin')
            .set(auth.provider.key, auth.provider.encode({ name: 'bob', password: 'bob' }))
            .expect(403) //Forbidden : bad claims 
            .end((error) => {
                if (error) throw error;
            })

        request.get('/bye')
            .expect('bye')
            .end((error) => {
                if (error) throw error;
                done();
            })
    })
开发者ID:D10221,项目名称:kua,代码行数:55,代码来源:kompose_test.ts

示例14: helmetTest

/**
 * @summary Test for {@see helmet}.
 */
function helmetTest() {
    app.use(helmet());
    app.use(helmet({}));
    app.use(helmet({ frameguard: false }));
    app.use(helmet({ frameguard: true }));
    app.use(helmet({
      frameguard: {
        action: 'deny'
      }
    }));
}
开发者ID:AbraaoAlves,项目名称:DefinitelyTyped,代码行数:14,代码来源:koa-helmet-tests.ts

示例15: async

const main = async () => {
    const app = new Koa();
    const router = new Router();
    const apolloServer = new ApolloServer({
        formatError: err => {
            logger.error(err);
            return err;
        },
        schema: Schema,
        playground: {
            endpoint: "/tictactoe/graphql"
        }
    });
    apolloServer.applyMiddleware({ app });

    app.use(koabody());

    router.get("/ping", async ctx => {
        ctx.body = "pong";
    });

    app.use(router.routes());

    app.use(koaBunyanLogger());
    app.use(koaBunyanLogger.requestLogger());

    process.on("unhandledRejection", err => {
        logger.error(err);
    });

    await connectWithRetry();
    const server = createServer(app.callback());

    SubscriptionServer.create(
        {
            schema: Schema,
            execute,
            subscribe
        },
        {
            server,
            path: "/ws"
        }
    );

    server.listen(3000, () => {
        logger.info("listening on 3000");
    });
};
开发者ID:mattcroberts,项目名称:tic-tac-toe,代码行数:49,代码来源:main.ts


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