Example #1
0
  it('should return json response', function(done) {
    done = pedding(2, done);
    const app = new koa();
    app.on('error', function() {});
    onerror(app, {
      accepts() {
        if (this.url.indexOf('.json') > 0) {
          return 'json';
        }
        return 'text';
      },
    });
    app.use(commonError);

    request(app.callback())
      .get('/user.json')
      .set('Accept', '*/*')
      .expect(500)
      .expect('Content-Type', 'application/json; charset=utf-8')
      .expect({ error: 'foo is not defined' }, done);

    request(app.callback())
      .get('/user')
      .set('Accept', 'application/json')
      .expect(500)
      .expect('Content-Type', 'text/plain; charset=utf-8')
      .expect('foo is not defined', done);
  });
Example #2
0
    it('responds with 501 Not Implemented using the "throw" option', function (done) {
      var app = new Koa();
      var router = new Router();
      app.use(router.routes());
      app.use(function (ctx, next) {
        return next().catch(function (err) {
          // assert that the correct HTTPError was thrown
          err.name.should.equal('NotImplementedError');
          err.statusCode.should.equal(501);

          // translate the HTTPError to a normal response
          ctx.body = err.name;
          ctx.status = err.statusCode;
        });
      });
      app.use(router.allowedMethods({ throw: true }));
      router.get('/users', function () {});
      router.put('/users', function () {});
      request(http.createServer(app.callback()))
      .search('/users')
      .expect(501)
      .end(function (err, res) {
        if (err) return done(err);
        // the 'Allow' header is not set when throwing
        res.header.should.not.have.property('allow');
        done();
      });
    });
Example #3
0
    run() {

        this.useErrorMessage.call(this);
        this.useRouterSettings.call(this);

        if (this.https) {
            let keys = {
                key: fs.readFileSync('./keys/localhost.key'),
                cert: fs.readFileSync('./keys/localhost.crt')
            };

            http2.createServer(keys, this.Koa.callback()).listen(this.port);
        } else {
            http.createServer(this.Koa.callback()).listen(this.port);
        }
    }
Example #4
0
  it('method: array', (done) => {
    const app = new Koa()
    app.use(res.pass([
      { method: ['GET', 'POST'], path: '/:name' }
    ]))
    app.use((ctx) => {
      ctx.body = 'ok'
    })

    request(app.callback())
      .post('/nswbmw')
      .expect(200)
      .end((err, res) => {
        assert.equal(err, null)
        assert.equal(res.text, 'ok')
        request(app.callback())
          .get('/nswbmw')
          .expect(200)
          .end((err, res) => {
            assert.equal(err, null)
            assert.equal(res.text, 'ok')
            done()
          })
      })
  })
Example #5
0
  it('registers multiple middleware for one route', function(done) {
    var app = new Koa();
    var router = new Router();

    router.get('/double', function(ctx, next) {
      return new Promise(function(resolve, reject) {
        setTimeout(function() {
          ctx.body = {message: 'Hello'};
          resolve(next());
        }, 1);
      });
    }, function(ctx, next) {
      return new Promise(function(resolve, reject) {
        setTimeout(function() {
          ctx.body.message += ' World';
          resolve(next());
        }, 1);
      });
    }, function(ctx, next) {
      ctx.body.message += '!';
    });

    app.use(router.routes());

    request(http.createServer(app.callback()))
      .get('/double')
      .expect(200)
      .end(function (err, res) {
        if (err) return done(err);
        expect(res.body.message).to.eql('Hello World!');
        done();
      });
  });
Example #6
0
  it('does not register middleware more than once (gh-184)', function (done) {
    var app = new Koa();
    var parentRouter = new Router();
    var nestedRouter = new Router();

    nestedRouter
      .get('/first-nested-route', function (ctx, next) {
        ctx.body = { n: ctx.n };
      })
      .get('/second-nested-route', function (ctx, next) {
        return next();
      })
      .get('/third-nested-route', function (ctx, next) {
        return next();
      });

    parentRouter.use('/parent-route', function (ctx, next) {
      ctx.n = ctx.n ? (ctx.n + 1) : 1;
      return next();
    }, nestedRouter.routes());

    app.use(parentRouter.routes());

    request(http.createServer(app.callback()))
      .get('/parent-route/first-nested-route')
      .expect(200)
      .end(function (err, res) {
        if (err) return done(err);
        expect(res.body).to.have.property('n', 1);
        done();
      });
  });
Example #7
0
  it('matches middleware only if route was matched (gh-182)', function (done) {
    var app = new Koa();
    var router = new Router();
    var otherRouter = new Router();

    router.use(function (ctx, next) {
      ctx.body = { bar: 'baz' };
      return next();
    });

    otherRouter.get('/bar', function (ctx) {
      ctx.body = ctx.body || { foo: 'bar' };
    });

    app.use(router.routes()).use(otherRouter.routes());

    request(http.createServer(app.callback()))
      .get('/bar')
      .expect(200)
      .end(function (err, res) {
        if (err) return done(err);
        expect(res.body).to.have.property('foo', 'bar');
        expect(res.body).to.not.have.property('bar');
        done();
      })
  });
Example #8
0
 it('executes route middleware using `app.context`', function (done) {
   var app = new Koa();
   var router = new Router();
   app.use(router.routes());
   router.use(function (ctx, next) {
     ctx.bar = 'baz';
     return next();
   });
   router.get('/:category/:title', function (ctx, next) {
     ctx.foo = 'bar';
     return next();
   }, function (ctx) {
     ctx.should.have.property('bar', 'baz');
     ctx.should.have.property('foo', 'bar');
     ctx.should.have.property('app');
     ctx.should.have.property('req');
     ctx.should.have.property('res');
     ctx.status = 204;
     done();
   });
   request(http.createServer(app.callback()))
   .get('/match/this')
   .expect(204)
   .end(function (err) {
     if (err) return done(err);
   });
 });
Example #9
0
async function serveWithKoa(project, options = {}) {
  const port = options.port || DEFAULT_PORT

  const swagger = await project.swagger()

  const app = new Koa()
  const router = koaRouter({
    prefix: swagger.basePath,
  })

  setupKoaRouter(project, router, swagger)

  app
    .use(router.routes())
    .use(router.allowedMethods())

  let server
  if (options.useSsl) {
    throw new Error('SSL server not yet supported')
  } else {
    server = http.createServer(app.callback()).listen(port)
  }

  project.log('info', `Listening on 127.0.0.1:${port}...`)

  return server
}
Example #10
0
  it('supports promises for async/await', function (done) {
    var app = new Koa();
    app.experimental = true;
    var router = Router();
    router.get('/async', function (ctx, next) {
      return new Promise(function (resolve, reject) {
        setTimeout(function() {
          ctx.body = {
            msg: 'promises!'
          };
          resolve();
        }, 1);
      });
    });

    app.use(router.routes()).use(router.allowedMethods());
    request(http.createServer(app.callback()))
      .get('/async')
      .expect(200)
      .end(function (err, res) {
        if (err) return done(err);
        expect(res.body).to.have.property('msg', 'promises!');
        done();
      });
  });
Example #11
0
    it('runs router middleware before subrouter middleware', function (done) {
      var app = new Koa();
      var router = new Router();
      var subrouter = new Router();

      router.use(function (ctx, next) {
        ctx.foo = 'boo';
        return next();
      });

      subrouter
        .use(function (ctx, next) {
          ctx.foo = 'foo';
          return next();
        })
        .get('/bar', function (ctx) {
          ctx.body = {
            foobar: ctx.foo + 'bar'
          };
        });

      router.use('/foo', subrouter.routes());
      app.use(router.routes());
      request(http.createServer(app.callback()))
        .get('/foo/bar')
        .expect(200)
        .end(function (err, res) {
          if (err) return done(err);

          expect(res.body).to.have.property('foobar', 'foobar');
          done();
        });
    });
Example #12
0
  it('_pathToRegexpOpts', (done) => {
    const app = new Koa()
    app.use(res.pass([
      { method: 'GET', path: '/:name' }
    ], {
      strict: true
    }))
    app.use((ctx) => {
      ctx.body = 'ok'
    })

    request(app.callback())
      .get('/nswbmw/')
      .expect(200)
      .end((err, res) => {
        assert.equal(err, null)
        assert.equal(res.body.data, 'ok')

        request(app.callback())
          .get('/nswbmw')
          .expect(200)
          .end((err, res) => {
            assert.equal(err, null)
            assert.equal(res.text, 'ok')
            done()
          })
      })
  })
Example #13
0
describe('plover-web/security/assert-method', () => {
  const app = new Koa();
  assertMethod(app);

  app.use(ctx => {
    if (ctx.path === '/post') {
      ctx.assertMethod('post');
    }
    if (ctx.path === '/get') {
      ctx.assertMethod(['get']);
    }
    ctx.body = 'ok';
  });

  const agent = request.agent(app.callback());

  it('test', () => {
    return co(function* () {
      yield agent.get('/get').expect('ok');
      yield agent.post('/get')
        .expect(401, 'invalid request method, expect: get, actual: POST');

      yield agent.post('/post').expect('ok');
      yield agent.get('/post').expect(401);
    });
  });
});
Example #14
0
  it('pass: function', (done) => {
    const app = new Koa()
    app.use(res.pass([
      { method: 'GET', path: '/:name', pass: (ctx) => { return ctx.path === '/nswbmw' } }
    ]))
    app.use((ctx) => {
      ctx.body = 'ok'
    })

    request(app.callback())
      .get('/nswbmw')
      .expect(200)
      .end((err, res) => {
        assert.equal(err, null)
        assert.equal(res.text, 'ok')

        request(app.callback())
          .get('/nswbmw1')
          .expect(200)
          .end((err, res) => {
            assert.equal(err, null)
            assert.equal(res.body.data, 'ok')
            done()
          })
      })
  })
Example #15
0
 it('supports promises for route middleware', function (done) {
   var app = new Koa();
   var router = new Router();
   app.use(router.routes());
   var readVersion = function () {
     return new Promise(function (resolve, reject) {
       var packagePath = path.join(__dirname, '..', '..', 'package.json');
       fs.readFile(packagePath, 'utf8', function (err, data) {
         if (err) return reject(err);
         resolve(JSON.parse(data).version);
       });
     });
   };
   router
     .get('/', function (ctx, next) {
       return next();
     }, function (ctx) {
       return readVersion().then(function () {
         ctx.status = 204;
       });
     });
   request(http.createServer(app.callback()))
   .get('/')
   .expect(204)
   .end(done);
 });
function test_Application() {
  const app = new Koa();
  const context: Context = app.context;
  // $ExpectError
  const _context: number = app.context;
  const callback: () => (req: http$IncomingMessage, res: http$ServerResponse) => void = app.callback;
  const handler: (req: http$IncomingMessage, res: http$ServerResponse) => void = app.callback();
  // $ExpectError
  const _callback: (req: http$IncomingMessage, res: http$ServerResponse) => void = app.callback;
  const env: string = app.env;
  // $ExpectError
  const _env: number = app.env;
  const keys: void|Array<string>|Object = app.keys;
  // $ExpectError
  const _keys: null = app.keys;
  const middleware: Array<Middleware> = app.middleware;
  // $ExpectError
  const _middleware: Middleware = app.middleware;
  const name: void|string = app.name;
  // $ExpectError
  const _name: number = app.name;
  const proxy: boolean = app.proxy;
  // $ExpectError
  const _proxy: number = app.proxy;
  const request: Request = app.request;
  // $ExpectError
  const _request: number = app.request;
  const response: Response = app.response;
  // $ExpectError
  const _response: number = app.response;
  const server: ServerType = app.server;
  // $ExpectError
  const _server: number = app.server;
  const subdomainOffset: number = app.subdomainOffset;
  // $ExpectError
  const _subdomainOffset: string = app.subdomainOffset;
  const listen: $PropertyType<ServerType, 'listen'> = app.listen;
  // $ExpectError
  const _listen: () => string = app.listen;
  const toJSON: () => ApplicationJSON = app.toJSON;
  // $ExpectError
  const _toJSON: () => string = app.toJSON;
  const inspect: () => ApplicationJSON = app.inspect;
  // $ExpectError
  const _inspect: () => string = app.inspect;
  app.use( (ctx, next) => {
    const ctx1: Context = ctx;
    // $ExpectError
    const _ctx1: number = ctx;
    const next1: () => Promise<void> = next;
    // $ExpectError
    const _next1: () => Promise<string> = next;
    return;
  });
  app.use(async (ctx, next) => {
    // $ExpectError
    return 'hello';
  });
}
Example #17
0
function requestPath(urlPath, status = 200, listener = app.callback()) {
  return new Promise(function(resolve, reject) {
    request(listener)
      .get(urlPath)
      .expect(status)
      .end(function(err, res) {
        if (err) reject(err)
        else resolve(res)
      })
  })
}
Example #18
0
  it('this.state in middleware will inherit app.context.state', function (done) {
    const app = new Koa()
    app.context.state = { 'foo': 'bar' }
    app.use(inheritState())
    app.use(function * () {
      should(this.state.foo).be.equal('bar')
      this.status = 204
    })

    request(app.callback()).get('/')
      .expect(204).end(done)
  })
Example #19
0
  it('should set headers from error.headers ok', function(done) {
    const app = new koa();
    app.on('error', function() {});
    onerror(app);
    app.use(headerError);

    request(app.callback())
      .get('/')
      .set('Accept', 'text/plain')
      .expect(500)
      .expect('foo', 'bar', done);
  });
Example #20
0
  it('should show status error when err.message not present', function(done) {
    const app = new koa();
    app.on('error', function() {});
    onerror(app);
    app.use(emptyError);

    request(app.callback())
      .get('/')
      .set('Accept', 'text/plain')
      .expect(500)
      .expect('Internal Server Error', done);
  });
Example #21
0
  it('should show error message ok', function(done) {
    const app = new koa();
    app.on('error', function() {});
    onerror(app);
    app.use(exposeError);

    request(app.callback())
      .get('/')
      .set('Accept', 'text/plain')
      .expect(500)
      .expect('this message will be expose', done);
  });
Example #22
0
 .end((err, res) => {
   assert.equal(err, null)
   assert.equal(res.text, 'ok')
   request(app.callback())
     .get('/')
     .expect(200)
     .end((err, res) => {
       assert.equal(err, null)
       assert.equal(res.body.data, 'ok')
       done()
     })
 })
Example #23
0
  it('should stream error ok', function(done) {
    const app = new koa();
    app.on('error', function() {});
    onerror(app);
    app.use(streamError);

    request(app.callback())
      .get('/')
      .set('Accept', 'text/plain')
      .expect(404)
      .expect(/ENOENT/, done);
  });
Example #24
0
  it('should common error ok', function(done) {
    const app = new koa();
    app.on('error', function() {});
    onerror(app);
    app.use(commonError);

    request(app.callback())
      .get('/')
      .set('Accept', 'text/plain')
      .expect(500)
      .expect('foo is not defined', done);
  });
Example #25
0
 test('ipFilter', async () => {
   const app = new Koa()
   app
     .use((ctx, next) => {
       ctx.request.ip = '127.0.0.1'
       return next()
     })
     .use(middleware.util)
     .use(middleware.ipFilter)
   const res = await request(app.callback()).get('/')
   expect(res.body.message).toBe('请求频率太快,已被限制访问')
 })
Example #26
0
 .end(function (err, res) {
   if (err) return done(err);
   expect(res.body).to.have.property('foobar', 'foobar');
   request(http.createServer(app.callback()))
     .get('/bar')
     .expect(200)
     .end(function (err, res) {
       if (err) return done(err);
       expect(res.body).to.have.property('foobar', 'foobar');
       done();
     });
 });
Example #27
0
 it('should always redirect to login page when session not exists', () => {
   const app = new koa();
   app.keys = ['i m secret'];
   app.use(userauth({
     match: '/user',
     loginURLFormater: () => 'http://auth.example.com/login',
     getUser: async () => null,
   }));
   return request(app.callback())
   .get('/user')
   .expect('Location', 'http://auth.example.com/login')
   .expect(302);
 });
Example #28
0
    it('it works', async function() {
      const app = new Koa()
      const router = new Router()
      router.augmentApp(app)
      const server = app.callback()

      app.get('/hello', function() {
        this.body = 'world'
      })

      const res = await request(server).get('/hello')
      res.text.should.equal('world')
    })
Example #29
0
    it('接入到其他koa应用', function() {
      const papp = plover(settings);

      papp.addMiddleware(function* () {
        this.body = 'hello plover';
      });

      const app = new Koa();
      app.use(papp.middleware());

      return request(app.callback())
        .get('/').expect('hello plover');
    });
Example #30
0
 it('should support match="" to match all', () => {
   const app = new koa();
   app.keys = ['i m secret'];
   app.use(session());
   app.use(userauth('', {
     loginURLFormater: () => 'http://auth.example.com/login',
     getUser: async () => null,
   }));
   return request(app.callback())
   .get('/')
   .expect('Location', '/login?redirect=%2F')
   .expect(302);
 });