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 made with es6/esm import
syntax.
Install ExpressX
npm install @jcbuisson/express-x
Our first server application
Now 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.createService('post', {
findUnique: prisma.Post.findUnique,
create: prisma.Post.create,
update: prisma.Post.update,
delete: prisma.Post.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
posts Post[]
}
model Post {
id Int @default(autoincrement()) @id
text String
author User @relation(fields: [authorId], references: [id], onDelete: Cascade)
authorId Int
}
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
. Of course you can other RDBMS such as PostGres, MySQL, MongoDB, etc.
Run the server
node app.js
It prints the following lines in the console:
App listening at http://localhost:8000
Create the 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 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()
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',
posts: [
{ id: 12, text: 'Post#1', authorId: 11 },
{ id: 13, text: 'Post#2', authorId: 11 }
]
}
We have a GraphQL-like experience with the nested posts, thanks to Prisma and its use through ExpressX services. We can harness the full power of Prisma from the client-side, without being constrained as we would with a simple REST API.
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 (post, 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 occurs on the completion of a call app.service('post').create()
on the server.