놀라운 express-decorator-router를 사용하여 익스프레스 애플리케이션을 분리합니다.
                                            
                                                
                                                
                                                
                                                
                                                
                                                 18669 단어  expressnodejavascript
                    
우리가 좋아하는 익스프레스를 위한 수많은 경로 파일이 지겨우신가요?
미들웨어를 사용하고 종속성을 간결하고 명확하게 주입하는 방법을 찾고 계십니까?
지능적으로 분리하여 프로젝트를 테스트하는 데 도움이 되는 패키지를 찾고 계십니까?
귀하의 문제는 여기에서 끝났습니다. 전제가 변환이 필요하지 않고 koa, express 또는 express API를 따르는 모든 패키지와 함께 사용할 수 있는 패키지를 제시합니다.

트랜스파일에서 벗어나고 싶고 그리운 바닐라 JS를 좋아하는 힙스터인 당신.
이 패키지는 하나는 경로 정의를 포함하고 다른 하나는 경로 요청/응답 프로세스를 처리하는 기능을 포함하는 두 개의 파일을 불필요하게 생성하지 않도록 하여 유지 관리가 더 간단하고 확장 가능한 코드를 남깁니다.
32kb만 축소되어(출처: bundlephobia ) "수동"방식으로 또는 매우 어려운 도구awilix를 사용하여 종속성을 주입할 수 있습니다.
멋진 친구! 하지만 실전에서 어떻게 사용할까요?
 
 아윌릭스 없이
먼저 루트 모드에 대해 이야기합시다 👨💻👩💻
 컨트롤러를 해당 기술에 등록하기 🧐
useControllers 메서드는 두 개의 매개변수를 사용합니다. 첫 번째는 라우팅 메커니즘이고 두 번째는 표현식의 패턴과 일치하는 모든 컨트롤러를 찾는 책임이 있는 glob 표현식입니다.
 서버.js
 const express = require('express')
const { resolve } = require('path')
const { useControllers } = require('express-decorator-router')
const app = express()
const router = express.Router()
app.use(express.json())
app.use('/api', useControllers({
    controllerExpression: `${resolve('src')}/**/controller.js`,
    router
}))
app.listen(3000, () => console.log('🔮 magic happens on port 3000'))
컨트롤러 함수는 위의 예에서 볼 수 있듯이 데코레이터를 클래스 메서드와 연결하여 데코레이터 정의를 만드는 고차 함수를 반환합니다.
 컨트롤러.js
 const {
    get,
    put,
    del,
    post,
    controller
} = require('express-decorator-router')
class UserController {
    getUsers(ctx) {
        return ctx.response.json({ message: 'get all users' })
    }
    postUser(ctx) {
        const { user } = ctx.response.body
        return ctx.response.json({ message: `create user with name ${user}` })
    }
    putUser(ctx) {
        const { id } = ctx.request.params
        const { user } = ctx.request.body
        return ctx.response.json({ message: `update user with name ${user} with id ${id}` })
    }
    deleteUser(ctx) {
        const { id } = ctx.request.params
        return ctx.response.json({ message: `delete user with id ${id}` })
    }
}
module.exports = controller('/users')(UserController, {
    getUsers: get(),
    postUser: post(),
    putUser: put('/:id'),
    deleteUser: del('/:id')
})
 아윌릭스와 함께
Awilix는 매우 간단한 API를 가지고 있습니다(하지만 호출할 수 있는 방법은 많습니다). 최소한 다음 3가지를 수행해야 합니다.
const express = require('express')
const { resolve } = require('path')
const { useControllers } = require('express-decorator-router')
const app = express()
const router = express.Router()
app.use(express.json())
app.use('/api', useControllers({
    controllerExpression: `${resolve('src')}/**/controller.js`,
    router
}))
app.listen(3000, () => console.log('🔮 magic happens on port 3000'))
const {
    get,
    put,
    del,
    post,
    controller
} = require('express-decorator-router')
class UserController {
    getUsers(ctx) {
        return ctx.response.json({ message: 'get all users' })
    }
    postUser(ctx) {
        const { user } = ctx.response.body
        return ctx.response.json({ message: `create user with name ${user}` })
    }
    putUser(ctx) {
        const { id } = ctx.request.params
        const { user } = ctx.request.body
        return ctx.response.json({ message: `update user with name ${user} with id ${id}` })
    }
    deleteUser(ctx) {
        const { id } = ctx.request.params
        return ctx.response.json({ message: `delete user with id ${id}` })
    }
}
module.exports = controller('/users')(UserController, {
    getUsers: get(),
    postUser: post(),
    putUser: put('/:id'),
    deleteUser: del('/:id')
})
삶을 더 쉽게 만들기 위해 이미 내부 종속성으로 제공되므로 동일한 것을 설치할 필요가 없습니다.
이제 응용 프로그램을 분리하는 것이 훨씬 더 간단해지는 방법을 살펴보겠습니다.
컨트롤러 등록이 훨씬 쉬워졌습니다 🤩
서버.js
const express = require('express')
const { resolve } = require('path')
const userService = require('./users/service')
const { useAwilixControllers, awilix, scopePerRequest } = require('express-decorator-router')
const app = express()
const router = express.Router()
const container = awilix.createContainer()
container.register({
    userService: awilix.asValue(userService).scoped()
})
app.use(express.json())
app.use(scopePerRequest(container))
app.use('/api/user', useAwilixControllers({
    controllerExpression: `${resolve('src')}/**/controller.js`,
    router
}))
app.listen(3200, () => console.log('🔮 magic happens on port 3200'))
컨트롤러.js
const {get, controller, inject } = require('express-decorator-router')
const getUsers = (req, res) => {
    const { userService } = req
    return res.json(userService.getUsers())
}
module.exports = controller('/users', inject('userService'))({
    getUsers
}, {
    getUsers: get()
})
이제 창의적으로 확장 가능하고 테스트 가능하며 분리된 애플리케이션을 발견할 수 있습니다.
이 패키지는 미들웨어 카테고리의 awesome-express 목록에서 찾을 수 있습니다.
라지카이말 / 굉장한 익스프레스
:octocat: 멋진 express.js 리소스의 선별된 목록
리포지토리 설명서를 더 자세히 살펴볼 수 있습니다.
루카스멘데슬 / 익스프레스 데코레이터 라우터
⚡ 자바스크립트 코드를 변환하지 않고 간단한 방법으로 데코레이터 사용
익스프레스 데코레이터 라우터
 
 
use decorators in a simple way without transpiling javascript code
 왜요?
고속 경로 생성을 자동화하기 위해 바닐라 자바스크립트를 사용하는 데코레이터 기능을 사용해 본 적이 있습니까?
express-decorator-router 패키지는 코드에서 프로세스를 변환할 필요 없이 간단하고 교훈적인 방식으로 이 문제를 해결했습니다.
이 패키지는 하나의 파일에는 경로 정의가 포함되고 다른 파일에는 경로 요청/응답 프로세스를 처리하는 기능이 있는 파일 두 개를 불필요하게 생성하지 않도록 하여 유지 관리가 더 간단하고 확장 가능한 코드를 남깁니다.
 용법
프로토타입 기반 컨트롤러에서 데코레이터를 사용하는 간단한 예를 들어 보겠습니다.
const {
  get,
  controller
} = require ('express-decorator-router')
const controllerFactoryDecorator = controller('/users')
class UsersController {
  constructor () {/*...class constructor definition*/}
        
  getUsers (ctx) {/*...process to get users (database, network, etc)*/}
       
  getUsersById (
 …
  
   View on GitHub
  
                
                    
        
    
    
    
    
    
                
                
                
                
                    
                        
                            
                            
                            Reference
                            
                            이 문제에 관하여(놀라운 express-decorator-router를 사용하여 익스프레스 애플리케이션을 분리합니다.), 우리는 이곳에서 더 많은 자료를 발견하고 링크를 클릭하여 보았다
                                
                                https://dev.to/wakeupmh/decouple-your-express-applications-using-the-amazing-express-decorator-router-35p2
                            
                            
                            
                                텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
                            
                            
                                
                                
                                 우수한 개발자 콘텐츠 발견에 전념
                                (Collection and Share based on the CC Protocol.)
                                
                                
                                우수한 개발자 콘텐츠 발견에 전념
                                (Collection and Share based on the CC Protocol.)
                            
                            
                        
                    
                
                
                
            
use decorators in a simple way without transpiling javascript code
Reference
이 문제에 관하여(놀라운 express-decorator-router를 사용하여 익스프레스 애플리케이션을 분리합니다.), 우리는 이곳에서 더 많은 자료를 발견하고 링크를 클릭하여 보았다 https://dev.to/wakeupmh/decouple-your-express-applications-using-the-amazing-express-decorator-router-35p2텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
                                
                                
                                
                                
                                
                                우수한 개발자 콘텐츠 발견에 전념
                                (Collection and Share based on the CC Protocol.)
                            
