本文整理汇总了TypeScript中koa-router.routes函数的典型用法代码示例。如果您正苦于以下问题:TypeScript routes函数的具体用法?TypeScript routes怎么用?TypeScript routes使用的例子?那么, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了routes函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的TypeScript代码示例。
示例1: constructor
/**
* Constructor
* @param application: the KOA application
*/
constructor (webServer: WebServer) {
this.webServer = webServer;
this.router = new KoaRouter();
// Create routes
this.openDevTools();
this.getVersion();
this.getOsPlatform();
this.getAddress();
this.getOpenedFile();
this.setOpenedFile();
webServer.localApplication.use(this.router.routes());
webServer.externApplication.use(this.router.routes());
}
示例2: 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())
}
示例3: 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");
});
};
示例4: Koa
app.prepare().then(() => {
const server = new Koa();
const router = new Router();
router.get('*', async ctx => {
await handle(ctx.req, ctx.res);
ctx.respond = false;
});
server.use(async (ctx, next) => {
ctx.res.statusCode = 200;
await next();
});
server.use(router.routes());
server.listen(port);
});
示例5: 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')
})
}
示例6: createConnection
createConnection().then(async connection => {
// create koa app
const app = new Koa();
const router = new Router();
// register all application routes
AppRoutes.forEach(route => router[route.method](route.path, route.action));
// run app
app.use(bodyParser());
app.use(router.routes());
app.use(router.allowedMethods());
app.listen(3000);
console.log("Koa application is up and running on port 3000");
}).catch(error => console.log("TypeORM connection error: ", error));
示例7: default
export default (app?: Koa) => {
const provided = !!app
const middlewares = [bodyParser(), router.routes(), router.allowedMethods()]
if (!app) {
app = new Koa()
app.keys = app.keys = (process.env.APP_KEYS || '').split(',')
middlewares.unshift(session({}, app))
}
if (provided) {
return middlewares
}
app.use(compose(middlewares))
app.listen(serverPort + 1, serverHost, () => {
debug('Router server is now running at %s:%s', serverHost, serverPort + 1)
})
}
示例8: webpackServeWaitpage
add: (app, middleware, options) => {
app.use(
webpackServeWaitpage(options, {
template: fs.readFileSync(
path.join(config.paths.gitRoot, 'webpack', 'config', 'waitpage.ejs'),
'utf8'
)
})
)
app.use(mount('/node_modules', serve(config.paths.nodeModules)))
app.use(
mount('/currencies', serve(path.join(config.paths.vendor, 'game-currency-formats', 'src')))
)
// Make sure the usage of webpack-serve-waitpage will be before the following commands if exists
middleware.webpack()
middleware.content()
app.use(router.routes())
}
示例9: createServer
function createServer() {
const app = new Koa();
app.use(bodyParser());
app.use(cors());
app.use(staticFiles(path.join(__dirname, 'public')));
const router = new Router();
router.get('/api/animals', async (ctx) => {
ctx.body = [
{id: 1, name: 'cat'},
{id: 2, name: 'dog'},
{id: 3, name: 'fish'}
];
});
app.use(async (ctx, next) => {
try {
await next();
} catch (err) {
const error = {
errorType: 'UNHANDLED_ERROR',
message: err.message,
stack: err.stack
};
ctx.body = error;
// tslint:disable-next-line:no-console
console.error(error);
}
});
app
.use(router.routes())
.use(router.allowedMethods());
return app;
}
示例10: Date
});
// logger
app.use(function *(next){
const start = new Date().getTime();
yield next;
const ms = new Date().getTime() - start;
console.log('%s %s - %s', this.method, this.url, ms);
});
// Redirect
redirect_router.redirect('/', '/static/main.html');
app.use(redirect_router.routes());
app.use(redirect_router.allowedMethods());
// static
app.use(mount('/static', serve('../frontend/build')));
// responses under /api
router.get('/hello', function *(next) {
this.body = 'hello';
});
function query_to_linestring(points) {
示例11: require
/// <reference path="./d.ts/node.d.ts" />
/// <reference path="./d.ts/koa.d.ts" />
import {YabpConfig} from './modules/config/config.ts';
import databaseSetup = require('./modules/db/databaseSetup.ts')
import koa = require('koa');
var router = require('koa-router');
var yabpServer = new koa();
router
.get("/REST/config/isConfigured", function* (next){
this.statusCode = 200;
this.set('Access-Control-Allow-Origin','http://localhost:9000')
this.body = { isConfigured : false };
})
yabpServer.use(router.routes()).use(router.allowedMethods());
yabpServer.listen(1988);
示例12: Router
import { ensureAuthenticated } from './authUtils';
import * as Router from 'koa-router';
import * as authController from './auth.controller';
import * as meController from './me.controller';
import * as github from './github';
import * as google from './google';
import * as facebook from './facebook';
import * as linkedin from './linkedin';
import * as live from './live';
import * as twitter from './twitter';
const router = new Router();
// routes
router.post('/login', authController.login);
router.post('/signup', authController.signup);
router.post('/github', github.authenticate);
router.post('/google', google.authenticate);
router.post('/facebook', facebook.authenticate);
router.post('/linkedin', linkedin.authenticate);
router.post('/live', live.authenticate);
router.post('/twitter', twitter.authenticate);
// auth only applied for following routes, not the routes above
router.use(['/me', '/unlink'], ensureAuthenticated);
router.get('/me', meController.getMe );
router.put('/me', meController.updateMe );
router.get('/unlink/:provider', meController.unlink);
export default router.routes();
示例13: saveVisitList
// record visit
if (whiteList[ctx.request.ip] === undefined) {
visitList[ctx.request.ip] = Date.now();
saveVisitList();
}
ctx.response.status = 200;
ctx.body = JSON.stringify({
statistics: { ...flavor },
code: 200
});
} catch (e) {
ctx.response.status = 400;
ctx.body = JSON.stringify(
{
message: e.message,
code: 400
},
null,
2
);
} finally {
fs.writeFileSync("./config.json", JSON.stringify(flavor, null, 2), "utf-8");
}
});
loadConfig();
app.use(Koabody());
app.use(router.routes()).listen(8080);
示例14: next
.post('/:url/unpublish', blogController.unpublish);
api.use(async (ctx, next) => {
let auth = ctx.headers.auth;
if (auth == Keys.api[ctx.method]) {
await next();
} else {
ctx.status = 401;
ctx.body = 'Unauthorized';
}
})
api.get('/counts', countController.list)
.post('/images', upload.single('file'), imageController.create)
.use('/games', game.routes(), game.allowedMethods())
.use('/gourmets', gourmet.routes(), gourmet.allowedMethods())
.use('/hearthstone-seasons', hearthstoneSeason.routes(), hearthstoneSeason.allowedMethods())
.use('/hearthstone-decks', hearthstoneDeck.routes(), hearthstoneDeck.allowedMethods())
.use('/hearthstone-matches', hearthstoneMatch.routes(), hearthstoneMatch.allowedMethods())
.get('/hearthstone-cards', hearthstoneCardController.list)
.post('/game-trophy', trophyController.scrap)
.use('/blogs', blog.routes(), blog.allowedMethods());
router.use('/api', api.routes(), api.allowedMethods())
.get('/admin*', auth({ name: Keys.admin.user, pass: Keys.admin.password }), async (ctx, next) => {
await send(ctx, 'admin.html', { root: path.join(__dirname, '..', '/public') });
})
.get('*', async (ctx, next) => {
await send(ctx, 'index.html', { root: path.join(__dirname, '..', '/public') });
})
示例15: Router
// Read more about routing at https://github.com/alexmingoia/koa-router
const router = new Router({prefix: '/api'});
router.get('/people', getAllPeople);
router.get('/todos', getAllTodo);
router.get('/todos/:id', getTodo);
router.post('/todos', addTodo);
router.patch('/todos/:id', patchTodo);
router.delete('/todos/:id', deleteTodo);
// Read more about koa at http://koajs.com/
const app = new Koa();
app.use(cors());
app.use(logger());
app.use(bodyParser());
app.use(router.routes());
// Read more about koa views at https://github.com/queckezz/koa-views
// Read more about Nunjucks at https://mozilla.github.io/nunjucks/
const viewPath = path.join(__dirname, 'views');
app.use(views(viewPath, {
map: {html: 'nunjucks'},
options: {loader: new FileSystemLoader(viewPath)}
}));
app.use(async (ctx, next) => {
// If nothing else was found, render index (assumption: single-page app)
await ctx.render('index');
});
const port: (number|string) = process.env.PORT || 8080;
app.listen(port, () => {