|
| 1 | +export default app => { |
| 2 | + if (typeof app.channel !== 'function') { |
| 3 | + // If no real-time functionality has been configured just return |
| 4 | + return; |
| 5 | + } |
| 6 | + |
| 7 | + app.on('connection', connection => { |
| 8 | + // On a new real-time connection, add it to the anonymous channel |
| 9 | + app.channel('anonymous').join(connection); |
| 10 | + }); |
| 11 | + |
| 12 | + app.on('login', (payload, { connection }) => { |
| 13 | + // connection can be undefined if there is no |
| 14 | + // real-time connection, e.g. when logging in via REST |
| 15 | + if (connection) { |
| 16 | + // Obtain the logged in user from the connection |
| 17 | + // const user = connection.user; |
| 18 | + |
| 19 | + // The connection is no longer anonymous, remove it |
| 20 | + app.channel('anonymous').leave(connection); |
| 21 | + |
| 22 | + // Add it to the authenticated user channel |
| 23 | + app.channel('authenticated').join(connection); |
| 24 | + |
| 25 | + // Channels can be named anything and joined on any condition |
| 26 | + |
| 27 | + // E.g. to send real-time events only to admins use |
| 28 | + // if(user.isAdmin) { app.channel('admins').join(connection); } |
| 29 | + |
| 30 | + // If the user has joined e.g. chat rooms |
| 31 | + // if(Array.isArray(user.rooms)) user.rooms.forEach(room => app.channel(`rooms/${room.id}`).join(channel)); |
| 32 | + |
| 33 | + // Easily organize users by email and userid for things like messaging |
| 34 | + // app.channel(`emails/${user.email}`).join(channel); |
| 35 | + // app.channel(`userIds/$(user.id}`).join(channel); |
| 36 | + } |
| 37 | + }); |
| 38 | + |
| 39 | + // eslint-disable-next-line no-unused-vars,arrow-body-style |
| 40 | + app.publish((data, context) => { |
| 41 | + // Here you can add event publishers to channels set up in `channels.js` |
| 42 | + // To publish only for a specific event use `app.publish(eventname, () => {})` |
| 43 | + // e.g. to publish all service events to all authenticated users use |
| 44 | + return app.channel('authenticated'); |
| 45 | + }); |
| 46 | + |
| 47 | + // Here you can also add service specific event publishers |
| 48 | + // e..g the publish the `users` service `created` event to the `admins` channel |
| 49 | + // app.service('users').publish('created', () => app.channel('admins')); |
| 50 | + |
| 51 | + // With the userid and email organization from above you can easily select involved users |
| 52 | + // app.service('messages').publish(() => { |
| 53 | + // return [ |
| 54 | + // app.channel(`userIds/${data.createdBy}`), |
| 55 | + // app.channel(`emails/${data.recipientEmail}`) |
| 56 | + // ]; |
| 57 | + // }); |
| 58 | +}; |
0 commit comments