temba 0.45.0 → 0.45.1

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 CHANGED
@@ -1,14 +1,10 @@
1
1
  # Temba
2
2
 
3
- [![Temba on NPM](https://img.shields.io/npm/v/temba)](https://www.npmjs.com/package/temba)
3
+ [![Temba on NPM](https://img.shields.io/npm/v/temba)](https://www.npmjs.com/package/temba) [![All Contributors](https://img.shields.io/badge/all_contributors-1-orange.svg?style=flat-square)](#contributors-) [![Documentation](https://img.shields.io/badge/Documentation-orange?logo=read-the-docs)](https://temba.bouwe.io)
4
4
 
5
- <!-- ALL-CONTRIBUTORS-BADGE:START - Do not remove or modify this section -->
6
5
 
7
- [![All Contributors](https://img.shields.io/badge/all_contributors-1-orange.svg?style=flat-square)](#contributors-)
8
6
 
9
- <!-- ALL-CONTRIBUTORS-BADGE:END -->
10
-
11
- **Get a simple REST API with zero coding in less than 30 seconds (seriously).**
7
+ **Create a simple REST API with zero coding in less than 30 seconds (seriously).**
12
8
 
13
9
  For developers that need a **quick NodeJS backend** for small projects.
14
10
 
@@ -18,37 +14,8 @@ An **OpenAPI specification** is generated and enabled by default, providing **in
18
14
 
19
15
  Data is kept **in memory**, but you can also store it in a **JSON file** or **MongoDB database**.
20
16
 
21
- ## Table of contents
22
-
23
- [Temba?](#temba-1)
24
-
25
- [Getting Started](#getting-started)
26
-
27
- [What Temba does](#what-temba-does)
28
-
29
- [Usage](#usage)
30
-
31
- [Config settings overview](#config-settings-overview)
32
-
33
- ## Temba?
34
-
35
- > _"Temba, at REST"_
36
-
37
- A metaphor for the declining of a gift, from the [Star Trek - The Next Generation episode "Darmok"](https://memory-alpha.fandom.com/wiki/Temba).
38
-
39
- In the fictional Tamarian language the word _"Temba"_ means something like _"gift"_.
40
-
41
17
  ## Getting Started
42
18
 
43
- Prerequisites you need to have:
44
-
45
- * Node
46
- * NPM
47
-
48
- - Optional: A MongoDB database, either locally or in the cloud
49
-
50
- ### Use the starter with `npx`
51
-
52
19
  Create your own Temba server instantly:
53
20
 
54
21
  ```
@@ -65,413 +32,16 @@ This command will:
65
32
  You’ll see:
66
33
 
67
34
  ```
68
- ✅ Server listening on port 3000
35
+ ✅ Server listening on port 8362
69
36
  ```
70
37
 
71
- Now you can send any HTTP request to any resource on localhost:3000 — and it just works.
38
+ Now you can send any HTTP request to any resource on localhost:8362 — and it just works.
72
39
 
73
40
  Or headover to the interactive OpenAPI specification of your API in your browser at `/openapi`.
74
41
 
75
- ### Adding to an existing app
76
-
77
- Alternatively, add Temba to your app manually:
78
-
79
- 1. `npm i temba`
80
-
81
- 2. Example code to create a Temba server:
82
-
83
- ```js
84
- import { create } from "temba"
85
- const server = await create()
86
- server.start()
87
- ```
88
-
89
- 3. In your console you'll see:
90
-
91
- ```
92
- ✅ Server listening on port 3000
93
- ```
94
-
95
- ### Configuration
96
-
97
- To opt-out or customize Temba's workings, pass a `config` object to the `create` function. Learn more in the [Usage](#usage) section, or check out the [config settings](#config-settings-overview).
98
-
99
- ## What Temba does
100
-
101
- Out of the box, Temba gives you a CRUD REST API to any resource name you can think of.
102
-
103
- Whether you `GET` either `/people`, `/movies`, `/pokemons`, or whatever, it all returns a `200 OK` with a `[]` JSON response. As soon as you `POST` a new resource, followed by a `GET` of that resource, the new resource will be returned. You can also `DELETE`, `PATCH`, or `PUT` resources by its ID.
104
-
105
- For every resource (`movies` is just an example), Temba supports the following requests:
106
-
107
- - `GET /movies` - Get all movies
108
- - `GET /movies/:id` - Get a movie by its ID
109
- - `POST /movies` - Create a new movie
110
- - `POST /movies:/id` - Create a new movie specifying the ID yourself
111
- - `PATCH /movies/:id` - Partially update a movie by its ID
112
- - `PUT /movies/:id` - Fully replace a movie by its ID
113
- - `DELETE /movies` - Delete all movies (if configured)
114
- - `DELETE /movies/:id` - Delete a movie by its ID
115
- - `HEAD /movies` - Get all movies, but without the response body
116
- - `HEAD /movies/:id` - Get a movie by its ID, but without the response body
117
-
118
- ### Supported HTTP methods
119
-
120
- The HTTP methods that are supported are `GET`, `POST`, `PATCH`, `PUT`, `DELETE`, and `HEAD`.
121
-
122
- On the root URI (e.g. http://localhost:8080/) only a `GET` request is supported, which shows you a message indicating the API is working. All other HTTP methods on the root URI return a `405 Method Not Allowed` response.
123
-
124
- ### JSON
125
-
126
- Temba supports JSON only.
127
-
128
- Request bodies sent with a `POST`, `PATCH`, and `PUT` requests are valid when the request body is either empty, or when it's valid formatted JSON. If you send a request with invalid formatted JSON, a `400 Bad Request` response is returned.
129
-
130
- Any valid formatted JSON is accepted and stored. If you want to validate or even change the JSON in the request bodies, check out [JSON Schema request body validation](#json-schema-request-body-validation) and the [`requestInterceptor`](#request-validation-or-mutation).
131
-
132
- IDs are auto generated when creating resources, unless you specify an ID in the `POST` request URL.
133
-
134
- Providing IDs in the request body of `POST`, `PUT`, or `PATCH` requests is not allowed and will return a `400 Bad Request` response. Instead, provide the ID in the request URL. However, omitting an ID in a `PUT` or `PATCH` request URL also returns a `400 Bad Request` response.
135
-
136
- ## Usage
137
-
138
- ### Data persistency
139
-
140
- By default data is stored in memory. This means the data is flushed when the server restarts. To persist your data, provide the `connectionString` config setting for your JSON file or MongoDB database.
141
-
142
- #### JSON file
143
-
144
- ```js
145
- const config = {
146
- connectionString: 'data.json',
147
- }
148
- const server = await create(config)
149
- ```
150
-
151
- All resources are saved in a single JSON file. The file is not created or updated unless you create, update, or delete resources.
152
-
153
- #### MongoDB
154
-
155
- ```js
156
- const config = {
157
- connectionString: 'mongodb://localhost:27017/myDatabase',
158
- }
159
- const server = await create(config)
160
- ```
161
-
162
- For every resource you use in your requests, a collection is created in the database. However, not until you actually create a resource with a `POST`.
163
-
164
- ### OpenAPI specification
165
-
166
- OpenAPI support in Temba is enabled by default, automatically generating both JSON and YAML specifications that accurately reflect your configured resources and settings.
167
-
168
- Alongside these specs, Temba serves interactive HTML documentation (i.e. Swagger UI) out of the box.
169
-
170
- OpenAPI support is controlled through the `openapi` setting, which accepts two forms:
171
-
172
- * **Boolean**
173
-
174
- * `true` (default) enables OpenAPI support.
175
- * `false` disables it completely.
176
-
177
- * **Object**
178
-
179
- * Supplying an object both enables OpenAPI **and** lets you customize the spec.
180
- * The object must adhere to the `OpenAPIObject` interface (see [openapi3-ts model](https://github.com/metadevpro/openapi3-ts/blob/71b55d772bacc58c127540b6a75d1b17a7ddadbb/src/model/openapi31.ts)).
181
- * Temba will deep-merge your custom specification into its default spec, preserving all auto-generated endpoints and schemas while applying your overrides.
182
-
183
- ### Allowing specific resources only
184
-
185
- If you only want to allow specific resource names, configure them by providing a `resources` key in the config object when creating the Temba server:
186
-
187
- ```js
188
- const config = {
189
- resources: ['movies', 'actors'],
190
- }
191
- const server = await create(config)
192
- ```
193
-
194
- Requests on these resources only give a `404 Not Found` if the ID does not exist. Requests on any other resource will always return a `404 Not Found`.
195
-
196
- ### API prefix
197
-
198
- With the `apiPrefix` config setting, all resources get an extra path segment in front of them. If the `apiPrefix` is `'api'`, then `/movies/12345` becomes `/api/movies/12345`:
199
-
200
- ```js
201
- const config = {
202
- apiPrefix: 'api',
203
- }
204
- const server = await create(config)
205
- ```
42
+ ## Documentation
206
43
 
207
- After configuring the `apiPrefix`, requests to the root URL (e.g. http://localhost:1234/), will now either return a `404 Not Found` on `GET` requests, or a `405 Method Not Allowed` for any other HTTP method.
208
-
209
- ### Static assets
210
-
211
- If you want to host static assets, for example a web app consuming the API, you can configure a `staticFolder`:
212
-
213
- ```js
214
- const config = {
215
- staticFolder: 'build',
216
- }
217
- const server = await create(config)
218
- ```
219
-
220
- With this setting, sending a `GET` request to the root URL, returns the content that is in the `'./build'` folder in your project, for example an HTML page.
221
-
222
- To prevent conflicts between the API resources and the web app routes, configuring a `staticFolder` also automatically sets the `apiPrefix` to "`api"`. Of course you can always change the `apiPrefix` to something else.
223
-
224
- ### JSON Schema request body validation
225
-
226
- By default, Temba does not validate request bodies.
227
-
228
- This means you can store your resources in any format you like. So creating the following two (very different) _movies_ is perfectly fine:
229
-
230
- ```
231
- POST /movies
232
- {
233
- "title": "O Brother, Where Art Thou?",
234
- "description": "In the deep south during the 1930s, three escaped convicts search for hidden treasure while a relentless lawman pursues them."
235
- }
236
-
237
- POST /movies
238
- {
239
- "foo": "bar",
240
- "baz": "boo"
241
- }
242
- ```
243
-
244
- You can even omit a request body when doing a `POST`, `PATCH`, or `PUT`. While this might be fine or even convenient when using Temba for prototyping, at some some point you might want to validate the request body.
245
-
246
- With the `schema` setting, you can define a [JSON Schema](https://json-schema.org/), per resource, and per request method. Here we define that when creating or replacing a movie, the `title` is required, the `description` is optional, and we don't allow any other fields. Updating movies has the same schema, except there are no required fields:
247
-
248
- ```js
249
- const schemaNewMovie = {
250
- type: 'object',
251
- properties: {
252
- title: { type: 'string' },
253
- description: { type: 'string' },
254
- },
255
- required: ['title'],
256
- additionalProperties: false,
257
- }
258
-
259
- const schemaUpdateMovie = { ...schemaNewMovie, required: [] }
260
-
261
- const config = {
262
- schema: {
263
- movies: {
264
- post: schemaNewMovie,
265
- put: schemaNewMovie,
266
- patch: schemaUpdateMovie,
267
- },
268
- },
269
- }
270
-
271
- const server = await create(config)
272
- ```
273
-
274
- If a request is not valid according to the schema, a `400 Bad Request` response is returned, and a message in the response body indicating the validation error.
275
-
276
- ### Intercepting requests
277
-
278
- In addition to (or instead of) validating the request using JSON Schema, you can also intercept the request before it is persisted, using the `requestInterceptor` setting.
279
-
280
- It allows you to implement your own validation, or even change the request body.
281
-
282
- ```js
283
- const config = {
284
- requestInterceptor: {
285
- get: ({ headers, resource, id }) => {
286
- //...
287
- },
288
- post: ({ headers, resource, id, body }) => {
289
- // Validate, or even change the request body
290
- },
291
- put: ({ headers, resource, id, body }) => {
292
- // Validate, or even change the request body
293
- },
294
- patch: ({ headers, resource, id, body }) => {
295
- // Validate, or even change the request body
296
- },
297
- delete: ({ headers, resource, id }) => {
298
- //...
299
- },
300
- },
301
- }
302
-
303
- const server = await create(config)
304
- ```
305
-
306
- The `requestInterceptor` is an object with fields for each of the HTTP methods you might want to intercept, and the callback function you want Temba to call, before processing the request, i.e. going to the database.
307
-
308
- Each callback function receives an object containing the request headers and the `resource` (e.g. `"movies"`). Depending on the HTTP method, also the `id` from the URL, and the request `body` are provided. `body` is a JSON object of the request body.
309
-
310
- > Request headers are not used by Temba internally when processing requests, so they are only passed into the `requestInterceptor` callback so you can do your own custom header validation.
311
-
312
- Your callback function can return the following things:
313
-
314
- - `void`: Temba will just save the request body as-is. An example of this is when you have validated the request body and everything looks fine.
315
- - `object`: Return an object if you want to change the request body. Temba will save the returned object instead of the original request body.
316
- - Throw an `Error` if you want to stop processing the request any further and return a `500 Internal Server Error` response. Or throw the custom `TembaError` to provide a status code.
317
-
318
- Example:
319
-
320
- ```js
321
- const config = {
322
- requestInterceptor: {
323
- post: ({ headers, resource, id, body }) => {
324
- // Add a genre to Star Trek films:
325
- if (resource === 'movies' && body.title.startsWith('Star Trek'))
326
- return { ...body, genre: 'Science Fiction' }
327
-
328
- // Throw a regular error for a 500 Internal Server Error status code
329
- if (resource === 'foobar') {
330
- throw new Error('Something went foobar')
331
- }
332
-
333
- // Throw a custom error to specify the status code
334
- if (resource === 'pokemons') {
335
- throw new TembaError('You are not allowed to create new Pokemons', 400)
336
- }
337
-
338
- // If you don't return anything, the original request will just be used.
339
- },
340
- },
341
- }
342
-
343
- const server = await create(config)
344
- ```
345
-
346
- ### Response body interception
347
-
348
- To change the response body of a `GET` request, before it's being sent to the client, configure a `responseBodyInterceptor`, and return the updated response body:
349
-
350
- ```js
351
- const config = {
352
- responseBodyInterceptor: ({ resource, body, id }) => {
353
- if (resource === 'movies') {
354
- if (id) {
355
- // response body is an object
356
- return {
357
- ...body,
358
- stuff: 'more stuff',
359
- }
360
- } else {
361
- // response body is an array
362
- return body.map((x) => ({
363
- ...x,
364
- stuff: 'more stuff',
365
- }))
366
- }
367
- }
368
-
369
- // If you end up here, the response body will just be returned unchanged.
370
- },
371
- }
372
-
373
- const server = await create(config)
374
- ```
375
-
376
- `responseBodyInterceptor` is a callback function that provides an object containing the `resource`, `body`, and the `id`. Depending on whether it's a collection or item request, the `body` is either an array or object, and the `id` can be `undefined`.
377
-
378
- In the example above we check for the `id` being defined, but a runtime check to determine the type of `body` would also suffice.
379
-
380
- Whatever you return in this function will become the response body and will be serialized as JSON and returned to the client.
381
-
382
- If you don't return anything, the response body will be sent as-is.
383
-
384
- The `responseBodyInterceptor` will only be called when the response was successful, i.e. a `200 OK` status code.
385
-
386
- ### Caching and consistency with Etags
387
-
388
- To optimize `GET` requests, and only send JSON over the wire when it changed, you can configure to enable Etags. Etags also prevent so-called mid-air collisions, where a client tries to update en item that has been updated by another client in the meantime:
389
-
390
- ```js
391
- const config = {
392
- etags: true,
393
- }
394
- const server = await create(config)
395
- ```
396
-
397
- After enabling etags, every `GET` request will return an `etag` response header, which clients can (optionally) send as an `If-None-Match` header with every subsequent `GET` request. Only if the resource changed in the meantime the server will return the new JSON, and otherwise it will return a `304 Not Modified` response with an empty response body.
398
-
399
- For updating or deleting items with a `PUT`, `PATCH`, or `DELETE`, after enabling etags, these requests are _required_ to provide an `If-Match` header with the etag. Only if the etag represents the latest version of the resource the update is made, otherwise the server responds with a `412 Precondition Failed` status code.
400
-
401
- ## Config settings overview
402
-
403
- Configuring Temba is optional, it already works out of the box.
404
-
405
- Here is an example of the config settings for Temba, and how you define them:
406
-
407
- ```js
408
- const config = {
409
- allowDeleteCollection: true,
410
- apiPrefix: 'api',
411
- connectionString: 'mongodb://localhost:27017/myDatabase',
412
- delay: 500,
413
- etags: true,
414
- openapi: true,
415
- port: 4321,
416
- requestInterceptor: {
417
- get: ({ headers, resource, id }) => {
418
- //...
419
- },
420
- post: ({ headers, resource, id, body }) => {
421
- // Validate, or even change the request body
422
- },
423
- put: ({ headers, resource, id, body }) => {
424
- // Validate, or even change the request body
425
- },
426
- patch: ({ headers, resource, id, body }) => {
427
- // Validate, or even change the request body
428
- },
429
- delete: ({ headers, resource, id }) => {
430
- //...
431
- },
432
- },
433
- resources: ['movies', 'actors'],
434
- responseBodyInterceptor: ({ resource, body, id }) => {
435
- // Change the response body before it is sent to the client
436
- },
437
- returnNullFields: false,
438
- schema: {
439
- movies: {
440
- post: {
441
- type: 'object',
442
- properties: {
443
- title: { type: 'string' },
444
- },
445
- required: ['title'],
446
- },
447
- },
448
- },
449
- staticFolder: 'build',
450
- }
451
- const server = await create(config)
452
- ```
453
-
454
- These are all the possible settings:
455
-
456
- | Config setting | Description | Default value |
457
- | :------------------------ | :------------------------------------------------------------------------------------------- | :--------------- |
458
- | `allowDeleteCollection` | Whether a `DELETE` request on a collection is allowed to delete all items. | `false` |
459
- | `apiPrefix` | See [API prefix](#api-prefix) | `null` | `'api'` |
460
- | `connectionString` | See [Data persistency](#data-persistency) | `null` |
461
- | `delay` | The delay, in milliseconds, after processing the request before sending the response. | `0` |
462
- | `etags` | See [Caching and consistency with Etags](#caching-and-consistency-with-etags) | `false` |
463
- | `openapi` | Enable or disable OpenAPI, or supply your custom spec object to merge into the default spec. | `true` |
464
- | `port` | The port your Temba server listens on | `3000` |
465
- | `requestInterceptor` | See [Request validation or mutation](#request-validation-or-mutation) | `noop` |
466
- | `resources` | See [Allowing specific resources only](#allowing-specific-resources-only) | `[]` |
467
- | `responseBodyInterceptor` | See [Response body interception](#response-body-interception) | `noop` |
468
- | `returnNullFields` | Whether fields with a null value should be returned in responses. | `true` |
469
- | `schema` | See [JSON Schema request body validation](#json-schema-request-body-validation) | `null` |
470
- | `staticFolder` | See [Static assets](#static-assets) | `null` |
471
-
472
- ## Under the hood
473
-
474
- Temba is built with TypeScript, [Node](https://nodejs.org), [Vitest](https://vitest.dev/), [Supertest](https://www.npmjs.com/package/supertest), [@rakered/mongo](https://www.npmjs.com/package/@rakered/mongo), and [lowdb](https://www.npmjs.com/package/lowdb).
44
+ Find full usage guides, configuration options, API reference, JSON Schema validation examples, interceptor recipes, MongoDB integration tips, and more on our dedicated docs site: [https://temba.bouwe.io](https://temba.bouwe.io)
475
45
 
476
46
  ## Contributors ✨
477
47
 
@@ -492,3 +62,7 @@ Thanks goes to these wonderful people ([emoji key](https://allcontributors.org/d
492
62
  <!-- ALL-CONTRIBUTORS-LIST:END -->
493
63
 
494
64
  This project follows the [all-contributors](https://github.com/all-contributors/all-contributors) specification. Contributions of any kind welcome!
65
+
66
+ # License
67
+
68
+ MIT, see [LICENSE](https://github.com/bouwe77/temba/blob/main/LICENSE).
package/config/index.js CHANGED
@@ -8,7 +8,7 @@ const defaultConfig = {
8
8
  requestInterceptor: null,
9
9
  responseBodyInterceptor: null,
10
10
  returnNullFields: true,
11
- port: 3000,
11
+ port: 8362,
12
12
  schemas: null,
13
13
  allowDeleteCollection: false,
14
14
  etagsEnabled: false,
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "temba",
3
- "version": "0.45.0",
4
- "description": "Get a simple REST API with zero coding in less than 30 seconds (seriously).",
3
+ "version": "0.45.1",
4
+ "description": "Create a simple REST API with zero coding in less than 30 seconds (seriously).",
5
5
  "type": "module",
6
6
  "main": "dist/src/index.js",
7
7
  "scripts": {
package/version.js CHANGED
@@ -1,2 +1,2 @@
1
- export const version = 'v0.45.0'
1
+ export const version = 'v0.45.1'
2
2