@jcbuisson/express-x-client 1.0.10 → 1.5.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md ADDED
File without changes
package/package.json CHANGED
@@ -1,21 +1,25 @@
1
1
  {
2
2
  "name": "@jcbuisson/express-x-client",
3
- "version": "1.0.10",
4
- "description": "",
3
+ "version": "1.5.2",
5
4
  "type": "module",
5
+ "description": "Client library for ExpressX framework",
6
6
  "main": "src/index.mjs",
7
- "repository": {
8
- "type": "git",
9
- "url": "git@gitlab.com:buisson31/express-x-client.git"
7
+ "test": "node --test",
8
+ "scripts": {
9
+ "test": "node --test",
10
+ "generate": "npx prisma generate",
11
+ "migrate": "npx prisma migrate dev --name init"
10
12
  },
11
- "author": "Jean-Christophe Buisson <buisson@enseeiht.fr> (jcbuisson.dev)",
12
- "license": "MIT",
13
- "private": false,
14
13
  "keywords": [],
14
+ "author": "",
15
+ "license": "ISC",
15
16
  "dependencies": {
16
- "socket.io-client": "^4.6.0",
17
+ "@jcbuisson/express-x": "^1.4.0",
18
+ "@prisma/client": "^4.16.1",
19
+ "axios": "^1.4.0",
20
+ "body-parser": "^1.20.2",
21
+ "prisma": "^4.16.1",
22
+ "socket.io-client": "^4.7.1",
17
23
  "uuid": "^9.0.0"
18
- },
19
- "devDependencies": {
20
24
  }
21
25
  }
package/prisma/dev.db ADDED
Binary file
@@ -0,0 +1,17 @@
1
+ -- CreateTable
2
+ CREATE TABLE "User" (
3
+ "id" INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT,
4
+ "name" TEXT NOT NULL,
5
+ "email" TEXT NOT NULL
6
+ );
7
+
8
+ -- CreateTable
9
+ CREATE TABLE "Post" (
10
+ "id" INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT,
11
+ "text" TEXT NOT NULL,
12
+ "authorId" INTEGER NOT NULL,
13
+ CONSTRAINT "Post_authorId_fkey" FOREIGN KEY ("authorId") REFERENCES "User" ("id") ON DELETE CASCADE ON UPDATE CASCADE
14
+ );
15
+
16
+ -- CreateIndex
17
+ CREATE UNIQUE INDEX "User_email_key" ON "User"("email");
@@ -0,0 +1,3 @@
1
+ # Please do not edit this file manually
2
+ # It should be added in your version-control system (i.e. Git)
3
+ provider = "sqlite"
@@ -0,0 +1,22 @@
1
+ generator client {
2
+ provider = "prisma-client-js"
3
+ }
4
+
5
+ model User {
6
+ id Int @default(autoincrement()) @id
7
+ name String
8
+ email String @unique
9
+ posts Post[]
10
+ }
11
+
12
+ model Post {
13
+ id Int @default(autoincrement()) @id
14
+ text String
15
+ author User @relation(fields: [authorId], references: [id], onDelete: Cascade)
16
+ authorId Int
17
+ }
18
+
19
+ datasource db {
20
+ provider = "sqlite"
21
+ url = "file:./dev.db"
22
+ }
package/src/index.mjs CHANGED
@@ -1,7 +1,7 @@
1
1
 
2
2
  import { v4 } from 'uuid'
3
3
 
4
- function expressxClient(socket, options={}) {
4
+ export default function expressXClient(socket, options={}) {
5
5
  if (options.debug === undefined) options.debug = false
6
6
 
7
7
  const waitingPromisesByUid = {}
@@ -20,9 +20,60 @@ function expressxClient(socket, options={}) {
20
20
  // on connection
21
21
  socket.on("connected", async (connectionId) => {
22
22
  if (options.debug) console.log('connected', connectionId)
23
+ // look in sessionStorage for a previously stored connection id
24
+ const prevConnectionId = sessionStorage.getItem('expressx-cnx-id')
25
+ if (prevConnectionId) {
26
+ // it's a reconnection
27
+ if (prevConnectionId < 0) {
28
+ // ask server to transfer all data from connection `prevConnectionId` to connection `connectionId`
29
+ if (options.debug) console.log('cnx-transfer', -prevConnectionId, 'to', connectionId)
30
+ socket.emit('cnx-transfer', {
31
+ from: -prevConnectionId,
32
+ to: connectionId,
33
+ })
34
+ } else {
35
+ if (options.debug) console.log('Error, previous connection id should be negative', prevConnectionId)
36
+ }
37
+
38
+ } else {
39
+ // set/update connection id in sessionStorage
40
+ sessionStorage.setItem('expressx-cnx-id', connectionId)
41
+ }
42
+ // call user-defined connection callback
23
43
  if (onConnectionCallback) onConnectionCallback(connectionId)
24
44
  })
25
45
 
46
+ socket.on("cnx-transfer-ack", async (connectionId) => {
47
+ if (options.debug) console.log('cnx-transfer-ack', connectionId)
48
+ sessionStorage.setItem('expressx-cnx-id', connectionId)
49
+ })
50
+
51
+
52
+ // A negative value for session storage 'expressx-cnx-id' means that the connection with the server has been lost
53
+ // Requests must wait until it goes positive again
54
+
55
+ // disconnection due to network issues
56
+ socket.on("disconnect", async (cause) => {
57
+ // alert('disconnect')
58
+ const id = sessionStorage.getItem('expressx-cnx-id')
59
+ if (id > 0) {
60
+ sessionStorage.setItem('expressx-cnx-id', -id)
61
+ } else {
62
+ if (options.debug) console.log('Error (disconnect), connection id should be negative', id)
63
+ }
64
+ })
65
+
66
+ // disconnection due to a page reload
67
+ window.addEventListener('unload', () => {
68
+ const id = sessionStorage.getItem('expressx-cnx-id')
69
+ if (id > 0) {
70
+ sessionStorage.setItem('expressx-cnx-id', -id)
71
+ } else {
72
+ if (options.debug) console.log('Error (unload), connection id should be negative', id)
73
+ }
74
+ })
75
+
76
+
26
77
  // on receiving response from service request
27
78
  socket.on('client-response', ({ uid, error, result }) => {
28
79
  if (options.debug) console.log('client-response', uid, error, result)
@@ -44,18 +95,32 @@ function expressxClient(socket, options={}) {
44
95
  if (handler) handler(result)
45
96
  })
46
97
 
98
+ function wait(ms) {
99
+ return new Promise(resolve => setTimeout(resolve, ms));
100
+ }
101
+
47
102
  async function serviceMethodRequest(name, action, ...args) {
48
- const uid = v4()
103
+ // wait while session storage 'expressx-cnx-id' is negative (= connection is lost with server)
104
+ let retries = 10
105
+ while (retries-- > 0) {
106
+ const id = sessionStorage.getItem('expressx-cnx-id')
107
+ if (id > 0) break
108
+ await wait(200)
109
+ }
110
+ if (retries === 0) throw new Error(`Timeout waiting for reconnection`)
111
+
49
112
  // create a promise which will resolve or reject by an event 'client-response'
113
+ const uid = v4()
50
114
  const promise = new Promise((resolve, reject) => {
51
115
  waitingPromisesByUid[uid] = [resolve, reject]
52
116
  // a 5s timeout may also reject the promise
53
117
  setTimeout(() => {
54
118
  delete waitingPromisesByUid[uid]
55
- reject(`Error: timeout on service '${name}', action '${action}', args: ${args}`)
119
+ reject(`Error: timeout on service '${name}', action '${action}', args: ${JSON.stringify(args)}`)
56
120
  }, 5000)
57
121
  })
58
122
  // send request to server through websocket
123
+ if (options.debug) console.log('client-request', uid, name, action, args)
59
124
  socket.emit('client-request', {
60
125
  uid,
61
126
  name,
@@ -93,5 +158,3 @@ function expressxClient(socket, options={}) {
93
158
  service,
94
159
  }
95
160
  }
96
-
97
- export default expressxClient
@@ -0,0 +1,136 @@
1
+
2
+ import bodyParser from 'body-parser'
3
+ import axios from 'axios'
4
+ import io from 'socket.io-client'
5
+ import { PrismaClient } from '@prisma/client'
6
+
7
+
8
+ import { describe, it, before, after } from 'node:test'
9
+ import { strict as assert } from 'node:assert'
10
+
11
+ import { expressX } from '@jcbuisson/express-x'
12
+ import expressXClient from '../src/index.mjs'
13
+
14
+ const prisma = new PrismaClient({
15
+ datasources: {
16
+ db: {
17
+ url: "file:./dev.db",
18
+ },
19
+ },
20
+ })
21
+
22
+ // `app` is a regular express application, enhanced with services and real-time features
23
+ const app = expressX(prisma)
24
+
25
+
26
+ describe('HTTP/REST API', () => {
27
+
28
+ let chris
29
+
30
+ before(async () => {
31
+ console.log("before")
32
+ // add body parsers for http requests
33
+ app.use(bodyParser.json())
34
+ app.use(bodyParser.urlencoded({ extended: false }))
35
+
36
+ app.createDatabaseService('User')
37
+ app.createDatabaseService('Post')
38
+
39
+ await app.service('User').deleteMany()
40
+ await app.service('Post').deleteMany()
41
+
42
+ // add http/rest endpoints
43
+ app.addHttpRest('/api/user', app.service('User'))
44
+ app.addHttpRest('/api/post', app.service('Post'))
45
+
46
+ await new Promise((resolve) => {
47
+ app.server.listen(8008, () => {
48
+ console.log(`App listening at http://localhost:8008`)
49
+ resolve()
50
+ })
51
+ })
52
+ })
53
+
54
+ after(() => {
55
+ console.log("after")
56
+ app.server.close()
57
+ })
58
+
59
+ it("can create a user", async () => {
60
+ const res = await axios.post('http://localhost:8008/api/user', {
61
+ name: "chris",
62
+ email: 'chris@mail.fr'
63
+ })
64
+ assert(res?.data?.name === 'chris')
65
+ })
66
+
67
+ it("can find users", async () => {
68
+ const res = await axios.get('http://localhost:8008/api/user')
69
+ assert(res?.data?.length > 0)
70
+ })
71
+
72
+ it("can find a user by name", async () => {
73
+ const res = await axios.get('http://localhost:8008/api/user?name=chris')
74
+ assert(res?.data?.length > 0)
75
+ chris = res.data[0]
76
+ })
77
+
78
+ it("can find a user by id", async () => {
79
+ const res = await axios.get(`http://localhost:8008/api/user/${chris.id}`)
80
+ assert(res?.data?.id === chris.id)
81
+ })
82
+
83
+ it("can patch a user", async () => {
84
+ const res = await axios.patch(`http://localhost:8008/api/user/${chris.id}`, {
85
+ name: "Christophe",
86
+ })
87
+ assert(res?.data?.name === "Christophe")
88
+ })
89
+
90
+ it("can delete a user", async () => {
91
+ const res = await axios.delete(`http://localhost:8008/api/user/${chris.id}`)
92
+ assert(res?.data?.name === "Christophe")
93
+ })
94
+
95
+ after(async () => {
96
+ app.server.close()
97
+ })
98
+ })
99
+
100
+
101
+ // test compatibility with client API
102
+ describe('Client API', () => {
103
+
104
+ let clientApp, socket
105
+
106
+ before(async () => {
107
+ await new Promise((resolve) => {
108
+ app.server.listen(8008, () => {
109
+ console.log(`App listening at http://localhost:8008`)
110
+ resolve()
111
+ })
112
+ })
113
+
114
+ socket = io('http://localhost:8008', { transports: ["websocket"] })
115
+ clientApp = expressXClient(socket)
116
+ })
117
+
118
+ after(async () => {
119
+ app.server.close()
120
+ })
121
+
122
+ it("can create a user", async () => {
123
+ const user = await clientApp.service('User').create({
124
+ data: {
125
+ name: "chris",
126
+ email: 'chris@mail.fr'
127
+ },
128
+ })
129
+ assert(user.name === 'chris')
130
+ })
131
+
132
+ after(async () => {
133
+ await socket.close()
134
+ await app.server.close()
135
+ })
136
+ })