-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcontroller.js
More file actions
301 lines (281 loc) · 10.9 KB
/
controller.js
File metadata and controls
301 lines (281 loc) · 10.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
/**
* A TinyPEN Controller. Actions here specifically fetch to the set TinyPEN API URLS.
* @see this.URLS
*
* @author Bryan Haberberger
* https://github.com/thehabes
*/
import { ObjectId } from 'mongodb'
let err_out = Object.assign(new Error(), {"status":123, "message":"N/A", "_dbaction":"N/A"})
class DatabaseController {
/** Basic constructor to establish constant class properties */
constructor() {
this.URLS = {}
this.URLS.CREATE = process.env.TINYPEN+"create"
this.URLS.UPDATE = process.env.TINYPEN+"update"
this.URLS.OVERWRITE = process.env.TINYPEN+"overwrite"
this.URLS.QUERY = process.env.TINYPEN+"query"
this.URLS.DELETE = process.env.TINYPEN+"delete"
console.log("TINY API established")
console.log(this.URLS)
}
/**
* Set the client for the controller and open a connection.
* Note TinyPEN is an open API on the internet. This controller has no connect().
* */
async connect() {
return
}
/**
* Close the connection to the client.
* Note TinyPEN is an open API on the internet. This controller has no close().
* */
async close() {
return
}
/**
* Generally check that the TinyPEN API is running.
* Perform a query for an object we know is there.
* @return boolean
* */
async connected() {
// Send a /query to ping TinyPen
try{
// FIXME something less expensive
const theone = await this.find({ "_id": "11111" })
return theone.length === 1
} catch(err){
console.error(err)
return false
}
}
reserveId(seed) {
try {
return new ObjectId(seed).toHexString()
} catch (err) {
return new ObjectId().toHexString()
}
}
/**
* Determine if the provided chars are a valid TinyPEN ID.
* @param id the string to check
* @return boolean
*/
isValidId(id) {
// Expect a String, Integer, or Hexstring-ish
try {
if (ObjectId.isValid(id)) { return true }
const intTest = Number(id)
if (!isNaN(intTest) && ObjectId.isValid(intTest)) { return true }
if (ObjectId.isValid(id.padStart(24, "0"))) { return true }
} catch(err) {
// just false
}
return false
}
asValidId(id) {
if (ObjectId.isValid(id)) { return id }
return id.toString().replace(/[^0-9a-f]/gi, "").substring(0,24).padStart(24, "0")
}
/**
* Use the TinyPEN query endpoint to find JSON objects matching the supplied property values.
* @param query JSON from an HTTP POST request. It must contain at least one property.
* @return the found JSON as an Array or Error
*/
async find(query) {
err_out._dbaction = this.URLS.QUERY
return await fetch(this.URLS.QUERY, {
method: 'post',
body: JSON.stringify(query),
headers: {
'Content-Type': 'application/ld+json; charset=utf-8'
}
})
.then(resp => {
if (!resp.ok) {
err_out.message = resp.statusText ?? `TinyPEN Query sent a bad response`
err_out.status = resp.status ?? 500
throw err_out
}
return resp.json()
})
.catch(err => {
// Specifically account for unexpected fetch()y things.
if(!err?.message) err.message = err.statusText ?? `TinyPEN Query did not complete successfully`
if(!err?.status) err.status = err.status ?? 500
if(!err?._dbaction) err._dbaction = this.URLS.QUERY
throw err
})
}
/**
* Use the TinyPEN create endpoint to create the supplied JSON object.
* TODO Pass forward the user bearer token from the Interfaced to TinyPEN?
* @return the created JSON or Error
*/
async save(data) {
err_out._dbaction = this.URLS.CREATE
return await fetch(this.URLS.CREATE, {
method: 'post',
body: JSON.stringify(data),
headers: {
'Content-Type': 'application/ld+json; charset=utf-8'
}
})
.then(resp => {
if (!resp.ok) {
err_out.message = resp.statusText ?? `TinyPEN Create sent a bad response`
err_out.status = resp.status ?? 500
throw err_out
}
return resp.json()
})
.catch(err => {
// Specifically account for unexpected fetch()y things.
if(!err?.message) err.message = err.statusText ?? `TinyPEN Create did not complete successfully`
if(!err?.status) err.status = err.status ?? 500
if(!err?._dbaction) err._dbaction = this.URLS.CREATE
throw err
})
}
/**
* Use the TinyPEN update endpoint to update the supplied JSON object.
* TODO Pass forward the user bearer token from the Interfaced to TinyPEN?
* @return the updated JSON or Error
*/
async update(data) {
err_out._dbaction = this.URLS.UPDATE
return await fetch(this.URLS.UPDATE, {
method: 'put',
body: JSON.stringify(data),
headers: {
'Content-Type': 'application/ld+json; charset=utf-8'
}
})
.then(resp => {
if (!resp.ok) {
err_out.message = resp.statusText ?? `TinyPEN Update sent a bad response`
err_out.status = resp.status ?? 500
throw err_out
}
return resp.json()
})
.catch(err => {
// Specifically account for unexpected fetch()y things.
if(!err?.message) err.message = err.statusText ?? `TinyPEN Update did not complete successfully`
if(!err?.status) err.status = err.status ?? 500
if(!err?._dbaction) err._dbaction = this.URLS.UPDATE
throw err
})
}
/**
* Use the TinyPEN overwrite endpoint to overwrite the supplied JSON object.
* Implements optimistic locking using If-Overwritten-Version header.
* TODO Pass forward the user bearer token from the Interfaced to TinyPEN?
* @return the updated JSON or Error
*/
async overwrite(data) {
err_out._dbaction = this.URLS.OVERWRITE
const headers = {
'Content-Type': 'application/ld+json; charset=utf-8'
}
// Add optimistic locking header if __rerum.isOverwritten exists
if (data.__rerum?.isOverwritten) {
headers['If-Overwritten-Version'] = data.__rerum.isOverwritten
}
return await fetch(this.URLS.OVERWRITE, {
method: 'put',
body: JSON.stringify(data),
headers
})
.then(resp => {
if (!resp.ok) {
if (resp.status === 409) {
// Handle optimistic locking conflict
return resp.json().then(errorData => {
const conflictError = new Error('Version conflict detected')
conflictError.status = 409
conflictError.currentVersion = errorData
conflictError._dbaction = this.URLS.OVERWRITE
throw conflictError
}).catch(jsonErr => {
// If we can't parse the error response, use the original error
err_out.message = resp.statusText ?? `Version conflict - document was modified by another process`
err_out.status = 409
throw err_out
})
}
err_out.message = resp.statusText ?? `TinyPEN Overwrite sent a bad response`
err_out.status = resp.status ?? 500
throw err_out
}
return resp.json()
})
.catch(err => {
// Re-throw structured errors (like version conflicts)
if (err.status === 409) {
throw err
}
// Specifically account for unexpected fetch()y things.
if(!err?.message) err.message = err.statusText ?? `TinyPEN Overwrite did not complete successfully`
if(!err?.status) err.status = err.status ?? 500
if(!err?._dbaction) err._dbaction = this.URLS.OVERWRITE
throw err
})
}
/**
* Use the TinyPEN delete endpoint to delete the supplied JSON object.
* TODO Pass forward the user bearer token from the Interfaced to TinyPEN?
* @return the created JSON or Error
*/
async remove(data) {
err_out._dbaction = this.URLS.DELETE
err_out.message = `Not yet implemented. Stay tuned.`
err_out.status = 501
throw err_out
// TODO
return await fetch(this.URLS.DELETE, {
method: 'delete',
body: JSON.stringify(data),
headers: {
'Content-Type': 'application/ld+json; charset=utf-8'
}
})
.then(resp => {
if (!resp.ok) {
err_out.message = resp.statusText ?? `TinyPEN DELETE sent a bad response`
err_out.status = resp.status ?? 500
throw err_out
}
return resp.text()
})
.catch(err => {
// Specifically account for unexpected fetch()y things.
if(!err?.message) err.message = err.statusText ?? `TinyPEN DELETE did not complete successfully`
if(!err?.status) err.status = err.status ?? 500
if(!err?._dbaction) err._dbaction = this.URLS.DELETE
throw err
})
}
}
/**
* OPTIMISTIC LOCKING IMPLEMENTATION
*
* This controller implements optimistic locking for TinyPen overwrite operations:
*
* 1. When fetching existing documents, check for __rerum.isOverwritten property
* 2. Include this value as "If-Overwritten-Version" header when calling overwrite/update
* 3. TinyPen will return 409 conflict if versions don't match
* 4. Error response includes currentVersion for potential retry
*
* Usage pattern in classes:
* ```javascript
* try {
* await databaseTiny.overwrite(updatedDoc)
* } catch (err) {
* if (err.status === 409) {
* // Handle version conflict - retry with currentVersion if needed
* }
* }
* ```
*/
export default DatabaseController