1const feathers = require('@feathersjs/feathers');
2const express = require('@feathersjs/express');
3const socketio = require('@feathersjs/socketio');
4
5// A messages service that allows to create new
6// and return all existing messages
7class MessageService {
8 constructor() {
9 this.messages = [];
10 }
11
12 async find () {
13 // Just return all our messages
14 return this.messages;
15 }
16
17 async create (data) {
18 // The new message is the data merged with a unique identifier
19 // using the messages length since it changes whenever we add one
20 const message = {
21 id: this.messages.length,
22 text: data.text
23 }
24
25 // Add new message to the list
26 this.messages.push(message);
27
28 return message;
29 }
30}
31
32// Creates an ExpressJS compatible Feathers application
33const app = express(feathers());
34
35// Parse HTTP JSON bodies
36app.use(express.json());
37// Parse URL-encoded params
38app.use(express.urlencoded({ extended: true }));
39// Host static files from the current folder
40app.use(express.static(__dirname));
41// Add REST API support
42app.configure(express.rest());
43// Configure Socket.io real-time APIs
44app.configure(socketio());
45// Register an in-memory messages service
46app.use('/messages', new MessageService());
47// Register a nicer error handler than the default Express one
48app.use(express.errorHandler());
49
50// Add any new real-time connection to the `everybody` channel
51app.on('connection', connection =>
52 app.channel('everybody').join(connection)
53);
54// Publish all events to the `everybody` channel
55app.publish(data => app.channel('everybody'));
56
57// Start the server
58app.listen(3030).on('listening', () =>
59 console.log('Feathers server listening on localhost:3030')
60);
61
62// For good measure let's create a message
63// So our API doesn't look so empty
64app.service('messages').create({
65 text: 'Hello world from the server'
66});
67