• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

TypeScript koa.use函数代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

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



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


示例16: connectDB

connectDB().then(() => {
    console.log('database connected')
    app.use(router.routes())
    http.createServer(app.callback()).listen(4000, () => {
        console.log(`http server listening on port: 4000`)
    })
})
开发者ID:YimYijet,项目名称:WebTest,代码行数:7,代码来源:index.ts


示例17: hstsTest

/**
 * @summary Test for {@see helmet#hsts} function.
 */
function hstsTest() {
    app.use(helmet.hsts());

    app.use(helmet.hsts({ maxAge: 7776000000 }));

    app.use(helmet.hsts({
      maxAge: 7776000000,
    }));

    app.use(helmet.hsts({
      maxAge: 7776000000,
      includeSubdomains: true
    }));

    app.use(helmet.hsts({
      maxAge: 7776000000,
      preload: true
    }));

    app.use(helmet.hsts({
      maxAge: 7776000000,
      force: true
    }));

    app.use(helmet.hsts({
      maxAge: 7776000000,
      setIf: (req, res) => true
    }));
}
开发者ID:AbraaoAlves,项目名称:DefinitelyTyped,代码行数:32,代码来源:koa-helmet-tests.ts


示例18: mount

 public async mount(app: Koa) {
   const mountPath = this.config.mountPath;
   const config: AuthConfig = {
     ...this.config,
     appPrefix: `${mountPath}/`,
   };
   const authApp = await createApp(config);
   app.use(koaMount(mountPath, authApp));
 }
开发者ID:Canner,项目名称:canner,代码行数:9,代码来源:app.ts


示例19: test

test('request an exsist file', async (t) => {
    const app = new Koa();
    app.use(serve('../'));

    const result = await request(app.listen())
        .get('/package.json')

    t.is(result.res.statusCode, 200);
});
开发者ID:hellopao,项目名称:koa-statics,代码行数:9,代码来源:index.ts


示例20: setRouters

export function setRouters(app: Koa, RouterClass: any[]): void {
  RouterClass.forEach(Router => {
    return new Router()
  })

  routerSet.forEach(Func => {
    Func()
  })

  app.use(koaRouter.routes())

  app.use(async (ctx) => {
    ctx.res.setHeader('Access-Control-Allow-Origin', ctx.request.header.origin || '*')
    ctx.res.setHeader('Access-Control-Allow-Credentials', 'true')
    ctx.res.setHeader('Access-Control-Allow-Methods', 'PUT, GET, POST, DELETE, OPTIONS')
    ctx.res.setHeader('Access-Control-Allow-Headers', 'Content-Type, X-Requested-With, AUTHORIZATION, X-Socket-Id')
  })
}
开发者ID:Brooooooklyn,项目名称:teambition-auth,代码行数:18,代码来源:router.ts



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


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
TypeScript koa.Context类代码示例发布时间:2022-05-25
下一篇:
TypeScript koa.on函数代码示例发布时间:2022-05-25
热门推荐
热门话题
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap