setupProcess.js

const setupProcess = (websocket) => {
    let state = 'idle'
    
    const startProcess = () => {
        state = 'running'

        websocket.onmessage = (event) => {
            const data = JSON.parse(event.data)
            // do something with data
        }
    }

    const stopProcess = () => {
        state = 'idle'
        websocket.onmessage = null
    }
}

module.exports = setupProcess

Dès que mon application démarre, ce module est initialisé avec le websocket.

app.js

const setupProcess = require('./setupProcess')
const router = require('./router')

const ws = require('ws')
const app = express()
const port = 3000
connectDatabase(mongoDbUrl)
app.use(router)

const ws = new WebSocket('wss//test-websocket.com/ws')
setupProcess(ws) // initialized

app.listen(port, () => {
    console.log(`Server is up on port ${port}`)
})

J'ai besoin d'exposer les méthodes startProcess et stopProcess dans setupProcess au routeur afin que l'utilisateur puisse démarrer ou arrêter le processus une fois qu'il a été initialisé dans app.js.

router.js

const express = require('express')
const router = new express.Router()

router.post('/process/start', async(req, res) => {
    // should be able to startProcess() from here
})

router.post('/process/start', async(req, res) => {
    // should be able to stopProcess from here
})

module.exports(router)

Comment puis-je modifier ma conception pour y parvenir? La seule chose à laquelle je peux penser est de faire de Process sa propre classe et de cette façon, il sera facile d'appeler des méthodes en son sein. J'apprécierais toutes les solutions, merci!

0
philosopher 29 oct. 2020 à 16:50

2 réponses

Meilleure réponse

Renvoie un objet depuis la fonction parent.

const setupProcess = (websocket) => {
    let state = 'idle'
    
    const startProcess = () => {
        state = 'running'

        websocket.onmessage = (event) => {
            const data = JSON.parse(event.data)
            // do something with data
        }
    }

    const stopProcess = () => {
        state = 'idle'
        websocket.onmessage = null
    }
    
    return {
      startProcess,
      stopPorcess
    }
    
}

module.exports = setupProcess

Ensuite, vous pouvez y accéder comme ça:

const setupProcess = require('./setupProcess')
const router = require('./router')

const ws = require('ws')
const app = express()
const port = 3000
connectDatabase(mongoDbUrl)

const ws = new WebSocket('wss//test-websocket.com/ws')
const methods = setupProcess(ws) // initialized

app.use(router(methods))



app.listen(port, () => {
    console.log(`Server is up on port ${port}`)
})

Router.js

const express = require('express')
const router = new express.Router()

module.exports = (methods) => {


    router.post('/process/start', async (req, res) => {
        // should be able to startProcess() from here
        //methods.startProcess();
    })

    router.post('/process/start', async (req, res) => {
        // should be able to stopProcess from here
        //methods.stopProcess();
    })

}
2
Marc 29 oct. 2020 à 14:00

Vous pouvez envelopper le module de routeur dans une fonction pour exposer les méthodes:

const express = require('express');

// require('./router')
// module.exports = 
const router = ({startProcess, stopProcess}) => {
    const router = new express.Router();
    
    router.post('/process/start', async(req, res) => {
        // should be able to startProcess() from here
    });

    router.post('/process/start', async(req, res) => {
        // should be able to stopProcess from here
    });
    return router;
}


// require('./setupProcess')
// module.exports = 
const setupProcess = (websocket) => {
    let state = 'idle'
    const startProcess = () => {
        state = 'running'
        websocket.onmessage = (event) => {
            const data = JSON.parse(event.data)
            // do something with data
        }
    }

    const stopProcess = () => {
        state = 'idle'
        websocket.onmessage = null
    }
    return {startProcess, stopProcess};
}


const ws = require('ws')
const app = express()
const port = 3000
connectDatabase(mongoDbUrl)

const ws = new WebSocket('wss//test-websocket.com/ws')
const methods = setupProcess(ws) // initialized


app.use(router(methods))

app.listen(port, () => console.log(`Server is up on port ${port}`))
1
Darth 29 oct. 2020 à 14:03