Как похудеть app.js в nodejs и koa2 - PullRequest
0 голосов
/ 25 мая 2018

У меня есть много кодов в файле app.js, и некоторые из них, например, следующие:

 const Router = require('koa-router')
 const router = new Router()
 router.get('/', async ( ctx )=>{ //lots of codes})
 router.get('/help', async ( ctx )=>{ //lots of codes})
 router.get('/signup', async ( ctx )=>{ //lots of codes})
 router.get('/signin', async ( ctx )=>{ //lots of codes})
 //and more codes

И теперь я хочу уменьшить app.js с этих маршрутизаторов, и я создаю папку с именем routers, и я создаю каждый файл js для каждого маршрутизатора, например help.js, signup.js, signin.js, и как я могу записать эти файлы маршрутизатора?и как я могу использовать их в app.js?

Ответы [ 2 ]

0 голосов
/ 01 июня 2018

Вы можете обработать ваш файл следующим образом:

index.js (содержит все маршруты) users.js, upload.js, stats.js и т. Д.

Давайте начнем сФайл users.js Здесь вы можете иметь несколько функций, например:

exports.getOne = async (ctx) => {
    // your custom code here
}

exports.getAll = async (ctx) => {
    // your custom code here
}

В вашем index.js

const Router = require('koa-router')
const router = new Router()
const users = require('./users')

router
   .get('/api/path/get', users.getOne)
   .get('/api/path/get', users.getAll)

Затем в вашем файле app.js вы получите:

const api = require('./api/index')

app.use(api.routes())
0 голосов
/ 01 июня 2018

Ваш help.js может выглядеть следующим образом:

'use strict';

exports.get = async (ctx, next) => {
    // your code goes here
}
exports.post = async (ctx, next) => {
    // your code goes here
}

В app.js вы можете сделать:

...

const help = require('./help'));

...

router
    .get('/help', help.get);
    .post('/help', help.post);
...