sleepy-serv 0.3.1 → 0.5.0

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/package.json CHANGED
@@ -2,7 +2,7 @@
2
2
  "name": "sleepy-serv",
3
3
  "description": "A more opinionated web server for building REST-ful applications",
4
4
  "author": "Travis J True",
5
- "version": "0.3.1",
5
+ "version": "0.5.0",
6
6
  "exports": "./src/index.js",
7
7
  "type": "module",
8
8
  "keywords": [
package/src/index.js CHANGED
@@ -4,7 +4,7 @@ import querystring from 'querystring'
4
4
  import readline from 'node:readline'
5
5
  import { stdin, stdout } from 'node:process'
6
6
 
7
- import * as _middleware from './middleware.js'
7
+ import * as _middleware from './middleware'
8
8
 
9
9
  import {
10
10
  NotFoundError,
@@ -13,15 +13,24 @@ import {
13
13
 
14
14
  export * from './errors'
15
15
 
16
- const ALLOWED_FILES_META = ['meta.js']
16
+ const ALLOWED_FILES_META = [
17
+ 'meta.js',
18
+ 'meta.ts',
19
+ ]
17
20
 
18
21
  const ALLOWED_FILES_METHODS = [
19
22
  'head.js',
23
+ 'head.ts',
20
24
  'get.js',
25
+ 'get.ts',
21
26
  'put.js',
27
+ 'put.ts',
22
28
  'post.js',
29
+ 'post.ts',
23
30
  'patch.js',
31
+ 'patch.ts',
24
32
  'delete.js',
33
+ 'delete.ts',
25
34
  ]
26
35
 
27
36
  const ALLOWED_FILES_ALL = [
@@ -192,13 +201,24 @@ ${route.modulePath}
192
201
 
193
202
  req.query = query ? querystring.parse(query) : {}
194
203
 
195
- for (const fn of middlewareChain) {
196
- const response = await fn(req, res)
204
+ const executeMiddleware = async (index) => {
205
+ const currentMiddleware = middlewareChain[index]
206
+ const isLastMiddleware = index === middlewareChain.length - 1
207
+
208
+ const next = !isLastMiddleware ?
209
+ () => executeMiddleware(index + 1)
210
+ : null
197
211
 
198
- if (response) {
199
- return response
212
+ const result = await currentMiddleware(req, res, next)
213
+
214
+ if (result instanceof Response) {
215
+ return result
216
+ } else {
217
+ throw new TypeError('Handler does not return a Response object')
200
218
  }
201
219
  }
220
+
221
+ return executeMiddleware(0)
202
222
  }
203
223
 
204
224
  return {
package/src/middleware.js CHANGED
@@ -2,6 +2,7 @@ import Ajv from 'ajv'
2
2
  import addFormats from 'ajv-formats'
3
3
 
4
4
  import {
5
+ BadRequestError,
5
6
  UnsupportedMediaTypeError,
6
7
  UnprocessableContentError,
7
8
  } from './errors'
@@ -46,14 +47,26 @@ function buildFormatterSchema (schema) {
46
47
  }
47
48
  }
48
49
 
49
- export async function parseJson (req, res) {
50
+ export async function parseJson (req, res, next) {
50
51
  const contentType = req.headers.get('content-type')
51
52
 
52
- if (req.method !== 'GET' && contentType !== 'application/json') {
53
+ if (!contentType) {
54
+ return next()
55
+ }
56
+
57
+ if (contentType !== 'application/json') {
53
58
  throw new UnsupportedMediaTypeError('content-type')
54
59
  }
55
60
 
56
- res.body = await req.json()
61
+ try {
62
+ res.body = await req.json()
63
+ } catch (err) {
64
+ console.error(err)
65
+
66
+ throw new BadRequestError('Body is invalid JSON')
67
+ }
68
+
69
+ return next()
57
70
  }
58
71
 
59
72
  export function setValidationFormats (formats) {
@@ -61,7 +74,7 @@ export function setValidationFormats (formats) {
61
74
  }
62
75
 
63
76
  export function validateSchema (schemas) {
64
- return function (req, res) {
77
+ return function (req, res, next) {
65
78
  const formattedSchemas = {
66
79
  headers: buildFormatterSchema(schemas.headers),
67
80
  params: buildFormatterSchema(schemas.params),
@@ -97,5 +110,7 @@ export function validateSchema (schemas) {
97
110
  if (errors.length > 0) {
98
111
  throw new UnprocessableContentError(errors)
99
112
  }
113
+
114
+ return next()
100
115
  }
101
116
  }
package/README.md DELETED
@@ -1,360 +0,0 @@
1
- # Sleepy Server
2
-
3
- A directory-driven web server designed for REST-ful applications
4
-
5
- ## Important Notes
6
-
7
- - This package requires [`bun.sh`](https://bun.sh) instead of NodeJS to run.
8
- - This project requires bun v1.2.3 or higher
9
-
10
- ## Getting Started
11
-
12
- Here's a minimalist example on how to create a sleepy-serv app:
13
-
14
- ```js
15
- import {
16
- middleware,
17
- createApp,
18
- } from 'sleepy-serv'
19
-
20
- const PORT = 3000
21
-
22
- const app = await createApp(PORT, import.meta.dirname)
23
- ```
24
-
25
- The parameter for `import.meta.dirname` can be any directory you prefer, but it's common to point to the same directory as your root `index.js` file. The next step is to create an `/api` directory in the directory that you point to, and begin adding routes.
26
-
27
- ### Return Value
28
-
29
- `sleepy-serv` was originally built for NodeJS, but it was ported to `bun` recently (before the initial release). The `createApp()` function merely calls `Bun.serve()` under-the-hood, and returns the `app` object that contains two properties:
30
- - `routes`: Contains a list of all of the routes defined by the file structure. This is useful for debugging.
31
- - `server`: this is the object that's returned from `Bun.serve()`. The `server` object has an `async` `.stop()` method on it, which can also be used for graceful shutdowns.
32
-
33
- ### Adding Routes
34
-
35
- Routes are made up as _resources_ and _methods_. Resources are described by a directory path, and methods are described by files created inside of those directories. Resource segments can also represent dynamic routing params by starting the directory name with a colon (`:`).
36
-
37
- Here's file structure example:
38
-
39
- ```
40
- /src
41
- index.js # this is where we called `createApp()`
42
- /api
43
- /users
44
- get.js
45
- post.js
46
- /:userId
47
- get.js
48
- delete.js
49
- put.js
50
- ```
51
-
52
- The file structure above create the following routes:
53
-
54
- - `GET /users`
55
- - `POST /users`
56
- - `GET /users/:userId`
57
- - `DELETE /users/:userId`
58
- - `PUT /users/:userId`
59
-
60
- These methods are supported:
61
-
62
- - GET
63
- - HEAD
64
- - PATCH
65
- - POST
66
- - PUT
67
- - DELETE
68
-
69
- ### Method Definition Files
70
-
71
- The route's logic is implemented in the route definition files. These must `export default` either a function, or an array of functions for middleware purposes. The function signature takes a `BunRequest` object, and must return a `BunResponse` object.
72
-
73
- Here's an example of a simple handler function:
74
-
75
- ```js
76
- export default function (req, res) {
77
- console.log('res:', res)
78
-
79
- return new Response('Hello world')
80
- }
81
- ```
82
-
83
- These functions take two parameters:
84
- - `req`: a `BunRequest` object
85
- - `res`: a results object
86
-
87
- The `res` parameter might seem familiar if coming from ExpressJS, but this parameter has a different purpose. The `res` parameter is meant to act as a dedicated, persistent object that middleware can write their results to. This way, the `req` object stays as a lean `BunRequest`.
88
-
89
- These handlers can also be `async` functions and `sleepy-serv` will wait for them to finish before moving on.
90
-
91
- ### Middleware
92
-
93
- As mentioned earlier, method definition files can also export an array of functions:
94
-
95
- ```js
96
- export default [
97
- async (req, res) => {
98
- res.body = await req.json()
99
- },
100
- (req, res) => {
101
- console.log('JSON body:', res.body)
102
-
103
- return new Response('Hello world')
104
- },
105
- ]
106
- ```
107
-
108
- This is useful if you want to break common logic up into reusable functions. The functions in the array are called in-order, and are provided the same `req` object. If you'd like to cache results between middleware functions, you can simply attach them to the `req` object.
109
-
110
- ### Breaking the Middleware Chain - Responses
111
-
112
- You might want to break the middleware chain with a response early.
113
-
114
- Here's an example:
115
-
116
- ```js
117
- export default [
118
- req => {
119
- if (req.params.userId === '123') {
120
- return new Response('Returned early')
121
- }
122
- },
123
- req => {
124
- return new Response('End of chain')
125
- },
126
- ]
127
- ```
128
-
129
- The the case above, the 1st middleware function will return a `Response` object if the route param's `userId` is equal to a specific value. In those cases, the last function in the middleware chain will not execute for that request.
130
-
131
- ### Breaking the Middleware Chain - Errors
132
-
133
- It's also common to throw errors for things like request validation or when a desired resource is not found. `sleepy-serv` has defined custom `Error` types for every type of 4xx and 5xx error:
134
-
135
- ```js
136
- import { NotFoundError } from 'sleepy-serv'
137
-
138
- export default async function (req) {
139
- const users = await sql`
140
- SELECT * FROM Users
141
- WHERE userId=${req.params.userId}
142
- `
143
-
144
- const foundUser = users[0]
145
-
146
- if (foundUser) {
147
- return new Response.json(foundUser)
148
- } else {
149
- throw new NotFoundError()
150
- }
151
- }
152
- ```
153
-
154
- If the user is found in the database, then the request will return with a successful response containing the user's data. If the user is not found, then the `NotFoundError()` is thrown which will automatically respond with a _404 NotFound_ error.
155
-
156
- Throwing generic errors also works too:
157
-
158
- ```js
159
- export default async function (req) {
160
- throw new Error('A problem occurred')
161
- }
162
- ```
163
-
164
- `sleepy-serv` will automatically respond with a _500 InternalServerError_ for any error types that aren't part of the `sleepy-serv` package.
165
-
166
- ## Metadata Modules
167
-
168
- It's also possible for resource directories to contain a `meta.js` file. These files can export various things that have some sort semantic relationship to the part of the route that they're defined in.
169
-
170
- ### Directory-Level Middleware
171
-
172
- `meta.js` files can also export an array of middleware functions:
173
-
174
- ```js
175
- // meta.js
176
-
177
- export const middleware = [
178
- req => { /* do middleware things */ },
179
- ]
180
- ```
181
-
182
- This middleware will be applied to all sibling and descendent method definition files within that directory.
183
-
184
- For example:
185
-
186
- ```
187
- /src
188
- index.js
189
- /api
190
- meta.js # metadata
191
- get.js
192
- /users
193
- meta.js # metadata
194
- get.js
195
- post.js
196
- /:userId
197
- meta.js # metadata
198
- get.js
199
- delete.js
200
- put.js
201
- ```
202
-
203
- The middleware defined in `/api/meta.js` will be applied by the following routes:
204
-
205
- - `GET /`
206
- - `GET /users`
207
- - `POST /users`
208
- - `GET /users/:userId`
209
- - `DELETE /users/:userId`
210
- - `PUT /users/:userId`
211
-
212
- The middleware defined in `/api/users/meta.js` will be applied the following routes:
213
-
214
- - `GET /users`
215
- - `POST /users`
216
- - `GET /users/:userId`
217
- - `DELETE /users/:userId`
218
- - `PUT /users/:userId`
219
-
220
- The middleware defined in `/api/users/:userId/meta.js` will be applied the following routes:
221
-
222
- - `GET /users/:userId`
223
- - `DELETE /users/:userId`
224
- - `PUT /users/:userId`
225
-
226
- ### Future Use-Cases
227
-
228
- At the time of this writing, `meta.js` only exports middleware functions.
229
-
230
- ## Build-In Middleware
231
-
232
- `sleepy-serv` also comes built-in with a few useful middleware functions that are commonly used.
233
-
234
- ### parseJson(req, _res)
235
-
236
- This middleware parses the request's `body` property as a JSON string, and then stores the results in `res.body`. Additional body parsers can be written in the future a accommodate other body encoding schemes.
237
-
238
- ### validateSchema(schemas)
239
-
240
- This function takes a `schemas` object. Each property is optional:
241
- - `headers`: takes a string formatter schema to evaulate `req.headers`
242
- - `params`: takes a string formatter schema to evaulate `req.params`
243
- - `query`: takes a string foramtter schema to evaulate `req.query`
244
- - `body`: takes a JSON validation schema to evaulate `res.body`
245
-
246
- Here's an example of the schema in action:
247
-
248
- ```
249
- PUT /contacts/123/addresses
250
-
251
- {
252
- street1: '123 Main St.',
253
- street2: '#100',
254
- city: 'Las Vegas',
255
- state: 'NV',
256
- postalCode: '12345',
257
- }
258
- ```
259
-
260
- ***
261
- TODO: add JSON schema example.
262
-
263
- Please take a look at the `lib/src/middleware.test.js` test file for a far a comprehensive set of examples on how to use this middleware.
264
- ***
265
-
266
- The `headers`, `params`, and `query` (querystrings) can only be strings, so they're evaulated using a simplified _string format schema_ instead of a full JSON schema.
267
-
268
- The string formatter schema looks like this:
269
-
270
- ```javascript
271
- {
272
- type: 'format',
273
- value: 'email',
274
- }
275
- ```
276
-
277
- **`type`**
278
-
279
- Can either set to `'format'` or `'pattern'`. The value of `type` determines how the `value` property is used.
280
-
281
- **`value`**
282
-
283
- This determines how to evaulate the string based on the `type` parameter. If `type` is set to `'format'`, then `value` can be set to one of the pre-defined formats that's provided by the JSON schema specification. If `type` is set to `'pattern'`, then `value` can be set to a regex pattern instead.
284
-
285
- Custom formats can also be provided by using the `setValidationFormats()` during app initialization. Here's an example:
286
-
287
- ```javascript
288
- middleware.setValidationFormats({
289
- phone: /^\d{10}$/, /* 10-digit, numeric string */
290
- postalCode: /^\d{5}$/, /* 5-digit, numeric string */
291
- })
292
- ```
293
-
294
- Calling `setValidationFormats()` extends the possible values that can be passed to the `value` property when evaulating strings in either the string formatter schema, or the `res.body`'s JSON schema.
295
-
296
- ## `createApp()` Options
297
-
298
- ### `hostname`
299
-
300
- The hostname can be customized like so:
301
-
302
- ```js
303
- createApp(import.meta.dirname, {
304
- hostname: 'test.sleepy-serv.com',
305
- })
306
- ```
307
-
308
- ### `mountPath`
309
-
310
- This adds a prefix to all routes. For example:
311
-
312
- ```js
313
- createApp(import.meta.dirname, {
314
- mountPath: 'api/public',
315
- })
316
- ```
317
-
318
- With the directory structure
319
-
320
- ```
321
- /src
322
- index.js # createApp()
323
- /api
324
- get.js
325
- /users
326
- get.js
327
- post.js
328
- ```
329
-
330
- Yields these routes:
331
-
332
- - `GET /api/public`
333
- - `GET /api/public/users`
334
- - `POST /api/public/users`
335
-
336
- ### `onClose`
337
-
338
- When the app is started, the app can be shutdown gracefully by pressing Ctrl+D in the terminal. The `onClose` hook will be called during that shutdown if it's defined. `onClose` can also be `async` as well.
339
-
340
- ```js
341
- const app = await createApp(PORT, import.meta.dirname, {
342
- onClose: () => console.info('closing down...'),
343
- })
344
- ```
345
-
346
- ## Running the Local Example App
347
-
348
- 1. Install [`bun.sh`](https://bun.sh)
349
- 1. Link the library package:
350
- - `$ cd lib`
351
- - `$ bun link`
352
- 1. Link the library to the project
353
- - `$ cd ../example`
354
- - `$ npm link sleepy-serv`
355
- 1. Finally, run the app: `$ bun --watch run start`
356
-
357
- ## Running Tests
358
-
359
- - Use `bun`'s built-in test runner
360
- - Run tests from the `./lib` directory