當前位置: 首頁>>代碼示例>>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;未經允許,請勿轉載。