1 | # dm-worker
|
2 | > Worker
|
3 |
|
4 | ## Usage
|
5 |
|
6 | 1. In project root create `worker.js`:
|
7 |
|
8 | ```js
|
9 | const conf = require('nconf')
|
10 | require('dm-sharedb-server/nconf')
|
11 |
|
12 | const path = require('path')
|
13 |
|
14 | // full path to workerActions.js and workerInit.js
|
15 | process.env['WORKER_ACTIONS_PATH'] = path.join(process.cwd(), './build/workerActions.js')
|
16 | process.env['WORKER_INIT_PATH'] = path.join(process.cwd(), './build/workerInit.js')
|
17 |
|
18 | const TaskDispatcher = require('dm-worker')
|
19 | const dispatcher = new TaskDispatcher()
|
20 |
|
21 | dispatcher.start().catch((err) => {
|
22 | console.log('Error starting worker', err)
|
23 | })
|
24 | ```
|
25 |
|
26 | 2. In project root create `workerInit.js`. Do any initializations here (plug in hooks, ORM, etc.).
|
27 | Since this file may be compiled by webpack, use `global.DM_WORKER_INIT` instead of `module.exports`:
|
28 |
|
29 | ```js
|
30 | import 'dm-sharedb-server/nconf'
|
31 | import ShareDB from 'sharedb'
|
32 | import richText from 'rich-text'
|
33 | import Racer from 'racer'
|
34 | import derbyAr from 'derby-ar'
|
35 | import ormEntities from './model'
|
36 | import shareDbHooks from 'sharedb-hooks'
|
37 | import hooks from './server/hooks'
|
38 |
|
39 | let init = global.DM_WORKER_INIT = function (backend) {
|
40 | // Register rich-text type in ShareDB
|
41 | ShareDB.types.register(richText.type)
|
42 |
|
43 | // Init ORM
|
44 | Racer.use(derbyAr)
|
45 | Racer.use(ormEntities)
|
46 | shareDbHooks(backend)
|
47 | hooks(backend)
|
48 | }
|
49 | ```
|
50 |
|
51 | 3. In project root create `workerActions.js`. Put your tasks here (name of functions are the name of tasks).
|
52 | Since this file may be compiled by webpack, use `global.DM_WORKER_ACTIONS` instead of `module.exports`:
|
53 |
|
54 | ```js
|
55 | let ACTIONS = global.DM_WORKER_ACTIONS = {}
|
56 |
|
57 | ACTIONS.test = function (model, task, done) {
|
58 | console.log('>> Start test task', task.id)
|
59 | setTimeout(() => {
|
60 | console.log('>> Finish test task', task.id)
|
61 | done()
|
62 | }, 5000)
|
63 | }
|
64 | ```
|
65 |
|
66 | 4. Add `worker`, `workerInit`, `workerActions` to `webpack.config.js` of `dm-react-webpack`:
|
67 |
|
68 | ```js
|
69 | module.exports = {
|
70 | // ...
|
71 |
|
72 | backendApps: {
|
73 | server: path.join(__dirname, 'server'),
|
74 | worker: path.join(__dirname, 'worker'),
|
75 | workerActions: path.join(__dirname, 'workerActions'),
|
76 | workerInit: path.join(__dirname, 'workerInit')
|
77 | }
|
78 |
|
79 | // ...
|
80 | }
|
81 | ```
|
82 |
|
83 | ## MIT Licence
|
84 |
|
85 | Copyright (c) 2017 Decision Mapper
|