Getting started
Create a project
Let's create a new folder for our application:
mkdir expressx-project
cd expressx-project
Since any ExpressX application is a Node application, we can create a default package.json using npm:
npm init es6 --yes
The es6
argument adds "type": "module"
in package.json
. Beware! All further module imports must be made with es6/esm import
syntax.
Install ExpressX
npm install @jcbuisson/express-x
Example using a relational database with Prisma
Create the backend server
We can create an ExpressX application which will provide a complete CRUD API on a User
resource backed in a Prisma database
// app.js
import { expressX } from '@jcbuisson/express-x'
import { PrismaClient } from '@prisma/client'
const prisma = new PrismaClient()
// `app` is a regular express application, enhanced with express-x services and real-time features
const app = expressX()
// create two CRUD database services with the Prisma methods: `create`, 'findUnique', etc.
app.createService('user', {
findUnique: prisma.User.findUnique,
create: prisma.User.create,
update: prisma.User.update,
delete: prisma.User.delete,
})
app.httpServer.listen(8000, () => console.log(`App listening at http://localhost:8000`))
Before running it we need to setup the corresponding database.
Create the database
Prisma is used in this example to talk to a relational database.
First, provide the database schema in prisma/schema.prisma
:
generator client {
provider = "prisma-client-js"
}
model User {
id Int @default(autoincrement()) @id
name String
}
datasource db {
provider = "sqlite"
url = "file:./dev.db"
}
Then create the database:
npx prisma db push
In this example which uses SQLite, the database file is created at prisma/dev.db
.
Run the server
node app.js
It prints the following lines in the console:
App listening at http://localhost:8000
Create the frontend client
We first need to install the client library:
npm install @jcbuisson/express-x-client socket.io-client
Create the following client NodeJS script:
// client.js
import io from 'socket.io-client'
import expressXClient from '@jcbuisson/express-x-client'
const socket = io('http://localhost:8000')
const app = expressXClient(socket)
async function main() {
const joe = await app.service('user').create({
data: {
name: "Joe"
}
})
console.log('joe', joe)
process.exit(0)
}
main()
For simplicity we use a node client, but you would write something similar with your favorite front-end framework.
You can use the exact same statements on services on the client side as you would on the server side, such as: app.service('user').create(...)
. Of course the app
object on the client is quite different that the app
object on the server; you can find explanations here.
Now run the client script:
node client.js
It prints the following lines in the console:
joe {
id: 11,
name: 'Joe',
}
We can harness the full power of Prisma from the client-side, without being constrained as we would with a simple REST API.
Example using a NoSQL database with CouchDB
Create the backend server
// app.js
import { expressX } from '@jcbuisson/express-x'
import NodeCouchDb from 'node-couchdb'
const couch = new NodeCouchDb({
auth: {
user: AUTHUSER,
pass: AUTHPASS
}
})
// `app` is a regular express application, enhanced with express-x services and real-time features
const app = expressX()
app.createService('couch', {
createDatabase: async (name) => await couch.createDatabase(name),
insert: async (dbname, doc) => await couch.insert(dbname, doc),
})
app.httpServer.listen(8000, () => console.log(`App listening at http://localhost:8000`))
Create the frontend client
// client.js
import io from 'socket.io-client'
import expressXClient from '@jcbuisson/express-x-client'
const socket = io('http://localhost:8000')
const app = expressXClient(socket)
async function main() {
try {
const result = await app.service('couch').insert("mydb", {
_id: "document_id",
field: ["sample", "data", true]
})
console.log('result', result)
} catch(err) {
console.log('err', err)
}
process.exit(0)
}
main()
Real-time applications
When a connected client calls a service method, two things happen on method completion:
- the resulting value is sent to the client
- an event is emitted, and sent to connected clients we'll call subscribers. The calling client may or not be one of those subscribers.
For example in a medical application, whenever a patients's record is modified, an event could be sent to all his/her caregivers.
Channels are used for this pub/sub mechanism. Service methods publish events on channels, and clients subscribe to channels in order to receive those events. ExpressX provides functions to configure which events are published to which channels. A channel is represented by a name and you can create and use as many channels as you need.
In the following example, every time a client connects to the server, it joins (= is subscribed to) the 'anonymous' channel. And whenever an event is emited by the post
or user
service, this event is published on this channel, and then broacasted to all connected clients, leading to real-time updates.
// app.js
import { expressX } from '@jcbuisson/express-x'
import { PrismaClient } from '@prisma/client'
const prisma = new PrismaClient()
// `app` is a regular express application, enhanced with express-x services and real-time features
const app = expressX(prisma)
// create two CRUD database services with the Prisma methods: `create`, 'update', etc
app.createService('user', {
findUnique: prisma.User.findUnique,
create: prisma.User.create,
update: prisma.User.update,
delete: prisma.User.delete,
})
app.createService('post', {
findUnique: prisma.Post.findUnique,
create: prisma.Post.create,
update: prisma.Post.update,
delete: prisma.Post.delete,
})
// publish
app.service('user').publish(async (user, context) => {
return ['anonymous']
})
app.service('post').publish(async (post, context) => {
return ['anonymous']
})
// subscribe
app.addConnectListener((socket) => {
app.joinChannel('anonymous', socket)
})
app.httpServer.listen(8000, () => console.log(`App listening at http://localhost:8000`))
Here is how a client may listen to channel events:
import io from 'socket.io-client'
import expressXClient from '@jcbuisson/express-x-client'
const socket = io('http://localhost:8000', { transports: ["websocket"] })
const app = expressXClient(socket)
app.service('user').on('create', (user) => {
console.log('User created', user)
})
app.service('post').on('create', (post) => {
console.log('Post created', post)
})
async function main() {
const user = await app.service('user').create({
data: {
name: "Joe"
}
})
await app.service('post').create({
data: {
authorId: user.id,
text: "Post#1"
}
})
await app.service('post').create({
data: {
authorId: user.id,
text: "Post#2"
}
})
const joe = await app.service('user').findUnique({
where: {
id: user.id,
},
include: {
posts: true,
},
})
console.log('joe', joe)
process.exit(0)
}
main()
The listener is triggered whenever the client receives from the server a create
event from the service post
. This event is sent to all subscribers after the execution of app.service('post').create()
on the server.