temba 0.8.2 → 0.10.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.
Files changed (43) hide show
  1. package/README.md +20 -17
  2. package/dist/README.md +324 -0
  3. package/dist/config/index.js +57 -73
  4. package/dist/config/index.js.map +1 -0
  5. package/dist/delay/delayMiddleware.js +16 -0
  6. package/dist/delay/delayMiddleware.js.map +1 -0
  7. package/dist/errors/errors.js +34 -0
  8. package/dist/errors/errors.js.map +1 -0
  9. package/dist/package.json +46 -0
  10. package/dist/queries/in-memory.js +48 -79
  11. package/dist/queries/in-memory.js.map +1 -0
  12. package/dist/queries/mongo.js +73 -277
  13. package/dist/queries/mongo.js.map +1 -0
  14. package/dist/queries/queries.js +17 -0
  15. package/dist/queries/queries.js.map +1 -0
  16. package/dist/routes/delete.js +37 -80
  17. package/dist/routes/delete.js.map +1 -0
  18. package/dist/routes/get.js +42 -81
  19. package/dist/routes/get.js.map +1 -0
  20. package/dist/routes/post.js +43 -61
  21. package/dist/routes/post.js.map +1 -0
  22. package/dist/routes/put.js +41 -88
  23. package/dist/routes/put.js.map +1 -0
  24. package/dist/routes/routes.js +56 -0
  25. package/dist/routes/routes.js.map +1 -0
  26. package/dist/routes/types.js +3 -0
  27. package/dist/routes/types.js.map +1 -0
  28. package/dist/routes/validator.js +20 -19
  29. package/dist/routes/validator.js.map +1 -0
  30. package/dist/server.js +72 -75
  31. package/dist/server.js.map +1 -0
  32. package/dist/urls/urlMiddleware.js +31 -0
  33. package/dist/urls/urlMiddleware.js.map +1 -0
  34. package/dist/urls/urlParser.js +11 -20
  35. package/dist/urls/urlParser.js.map +1 -0
  36. package/package.json +22 -15
  37. package/dist/delay/middleware.js +0 -16
  38. package/dist/errors/index.js +0 -21
  39. package/dist/errors/middleware.js +0 -14
  40. package/dist/logging/index.js +0 -38
  41. package/dist/queries/index.js +0 -21
  42. package/dist/routes/index.js +0 -95
  43. package/dist/urls/middleware.js +0 -42
package/README.md CHANGED
@@ -1,9 +1,8 @@
1
1
  # Temba
2
2
 
3
+ [![Temba on NPM](https://img.shields.io/npm/v/temba)](https://www.npmjs.com/package/temba)
3
4
  <!-- ALL-CONTRIBUTORS-BADGE:START - Do not remove or modify this section -->
4
-
5
5
  [![All Contributors](https://img.shields.io/badge/all_contributors-1-orange.svg?style=flat-square)](#contributors-)
6
-
7
6
  <!-- ALL-CONTRIBUTORS-BADGE:END -->
8
7
 
9
8
  **Get a simple MongoDB REST API with zero coding in less than 30 seconds (seriously).**
@@ -20,6 +19,8 @@ This project is inspired by the fantastic [json-server](https://github.com/typic
20
19
 
21
20
  [Getting Started](#getting-started)
22
21
 
22
+ [What Tema does](#what-temba-does)
23
+
23
24
  [Usage](#usage)
24
25
 
25
26
  ## Temba?
@@ -39,7 +40,7 @@ Prerequisites you need to have:
39
40
 
40
41
  > Wthout a database, Temba also works. However, then data is kept in memory and flushed every time the server restarts.
41
42
 
42
- ### Use `npx`
43
+ ### Use the starter with `npx`
43
44
 
44
45
  Create your own Temba server with the following command and you are up and running!
45
46
 
@@ -47,7 +48,7 @@ Create your own Temba server with the following command and you are up and runni
47
48
  npx create-temba-server my-rest-api
48
49
  ```
49
50
 
50
- With this command you clone the [Temba-starter](https://github.com/bouwe77/temba-starter) repository and install all dependencies.
51
+ This command clones the [Temba-starter](https://github.com/bouwe77/temba-starter) repository and installs all dependencies.
51
52
 
52
53
  ### Manually adding to an existing app
53
54
 
@@ -71,9 +72,7 @@ server.listen(port, () => {
71
72
 
72
73
  By passing a config object to the `create` function you can customize Temba's behavior. Refer to the [config settings](#config-settings-overview) below for the various possibilities.
73
74
 
74
- ## Usage
75
-
76
- ### Introduction
75
+ ## What Temba does
77
76
 
78
77
  Out of the box, Temba gives you a CRUD REST API to any resource name you can think of.
79
78
 
@@ -94,9 +93,21 @@ The HTTP methods that are supported are `GET`, `POST`, `PUT` and `DELETE`. For a
94
93
 
95
94
  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.
96
95
 
97
- ### MongoDB
96
+ ### JSON
97
+
98
+ Temba supports JSON only.
99
+
100
+ Request bodies sent with a `POST` and `PUT` requests are valid when the request body is either empty, or when it's valid formatted JSON. Adding a `Content-Type: application/json` header is required. If you send a request with invalid formatted JSON, a `400 Bad Request` response is returned.
101
+
102
+ Any valid formatted JSON is accepted and stored. If you want to validate or even change the JSON in the request bodies, check out the [`requestBodyValidator`](#request-body-validation-or-mutation) callbacks.
98
103
 
99
- When starting Temba, you can send your requests to it immediately. However, then the data resides in memory and is flushed as soon as the server restarts. To persist your data, provide the `connectionString` config setting for your MongoDB database:
104
+ IDs are auto generated when creating resources. IDs in the JSON request body are ignored for any request.
105
+
106
+ ## Usage
107
+
108
+ ### In-memory or MongoDB
109
+
110
+ 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 MongoDB database:
100
111
 
101
112
  ```js
102
113
  const config = {
@@ -118,14 +129,6 @@ const server = temba.create(config)
118
129
 
119
130
  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`.
120
131
 
121
- ### JSON
122
-
123
- Temba only supports JSON. If you send a request with invalid formatted JSON, a `400 Bad Request` response is returned.
124
-
125
- When sending JSON data (`POST` and `PUT` requests), adding a `Content-Type: application/json` header is required.
126
-
127
- IDs are auto generated when creating resources. IDs in the JSON request body are ignored.
128
-
129
132
  ### Static assets
130
133
 
131
134
  If you want to host static assets next to the REST API, configure the `staticFolder`:
package/dist/README.md ADDED
@@ -0,0 +1,324 @@
1
+ # Temba
2
+
3
+ [![Temba on NPM](https://img.shields.io/npm/v/temba)](https://www.npmjs.com/package/temba)
4
+ <!-- ALL-CONTRIBUTORS-BADGE:START - Do not remove or modify this section -->
5
+ [![All Contributors](https://img.shields.io/badge/all_contributors-1-orange.svg?style=flat-square)](#contributors-)
6
+ <!-- ALL-CONTRIBUTORS-BADGE:END -->
7
+
8
+ **Get a simple MongoDB REST API with zero coding in less than 30 seconds (seriously).**
9
+
10
+ For developers who need a quick backend for small projects.
11
+
12
+ Powered by NodeJS, Express and MongoDB.
13
+
14
+ This project is inspired by the fantastic [json-server](https://github.com/typicode/json-server) project, but instead of a JSON file Temba uses a real database. The goal, however, is the same: Get you started with a REST API very quickly.
15
+
16
+ ## Table of contents
17
+
18
+ [Temba?](#temba-1)
19
+
20
+ [Getting Started](#getting-started)
21
+
22
+ [What Tema does](#what-temba-does)
23
+
24
+ [Usage](#usage)
25
+
26
+ ## Temba?
27
+
28
+ > _"Temba, at rest"_
29
+
30
+ A metaphor for the declining of a gift, from the [Star Trek - The Next Generation, episode "Darmok"](https://memory-alpha.fandom.com/wiki/Temba).
31
+
32
+ In the fictional Tamarian language the word _"Temba"_ means something like _"gift"_.
33
+
34
+ ## Getting Started
35
+
36
+ Prerequisites you need to have:
37
+
38
+ - Node, NPM
39
+ - Optional: A MongoDB database, either locally or in the cloud
40
+
41
+ > Wthout a database, Temba also works. However, then data is kept in memory and flushed every time the server restarts.
42
+
43
+ ### Use the starter with `npx`
44
+
45
+ Create your own Temba server with the following command and you are up and running!
46
+
47
+ ```bash
48
+ npx create-temba-server my-rest-api
49
+ ```
50
+
51
+ This command clones the [Temba-starter](https://github.com/bouwe77/temba-starter) repository and installs all dependencies.
52
+
53
+ ### Manually adding to an existing app
54
+
55
+ Alternatively, add Temba to your app manually:
56
+
57
+ 1. `npm i temba`
58
+
59
+ 2. Example code to create a Temba server:
60
+
61
+ ```js
62
+ import temba from ("temba");
63
+ const server = temba.create();
64
+
65
+ const port = process.env.PORT || 3000;
66
+ server.listen(port, () => {
67
+ console.log(`Temba is running on port ${port}`);
68
+ });
69
+ ```
70
+
71
+ ### Configuration
72
+
73
+ By passing a config object to the `create` function you can customize Temba's behavior. Refer to the [config settings](#config-settings-overview) below for the various possibilities.
74
+
75
+ ## What Temba does
76
+
77
+ Out of the box, Temba gives you a CRUD REST API to any resource name you can think of.
78
+
79
+ 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`, or `PUT` resources by its ID.
80
+
81
+ For every resource (`movies` is just an example), Temba supports the following requests:
82
+
83
+ - `GET /movies` - Get all movies
84
+ - `GET /movies/:id` - Get a movie by its ID
85
+ - `POST /movies` - Create a new movie
86
+ - `PUT /movies/:id` - Update (fully replace) a movie by its ID
87
+ - `DELETE /movies` - Delete all movies
88
+ - `DELETE /movies/:id` - Delete a movie by its ID
89
+
90
+ ### Supported HTTP methods
91
+
92
+ The HTTP methods that are supported are `GET`, `POST`, `PUT` and `DELETE`. For any other HTTP method a `405 Method Not Allowed` response will be returned.
93
+
94
+ 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.
95
+
96
+ ### JSON
97
+
98
+ Temba supports JSON only.
99
+
100
+ Request bodies sent with a `POST` and `PUT` requests are valid when the request body is either empty, or when it's valid formatted JSON. Adding a `Content-Type: application/json` header is required. If you send a request with invalid formatted JSON, a `400 Bad Request` response is returned.
101
+
102
+ Any valid formatted JSON is accepted and stored. If you want to validate or even change the JSON in the request bodies, check out the [`requestBodyValidator`](#request-body-validation-or-mutation) callbacks.
103
+
104
+ IDs are auto generated when creating resources. IDs in the JSON request body are ignored for any request.
105
+
106
+ ## Usage
107
+
108
+ ### In-memory or MongoDB
109
+
110
+ 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 MongoDB database:
111
+
112
+ ```js
113
+ const config = {
114
+ connectionString: 'mongodb://localhost:27017',
115
+ }
116
+ const server = temba.create(config)
117
+ ```
118
+
119
+ For every resource you use in your requests, a collection is created in the database. However, not until you actually store (create) a resource with a `POST`.
120
+
121
+ ### Allowing specific resources only
122
+
123
+ If you only want to allow specific resource names, configure them by providing a `resourceNames` key in the config object when creating the Temba server:
124
+
125
+ ```js
126
+ const config = { resourceNames: ['movies', 'actors'] }
127
+ const server = temba.create(config)
128
+ ```
129
+
130
+ 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`.
131
+
132
+ ### Static assets
133
+
134
+ If you want to host static assets next to the REST API, configure the `staticFolder`:
135
+
136
+ ```js
137
+ const config = { staticFolder: 'build' }
138
+ const server = temba.create(config)
139
+ ```
140
+
141
+ This way, you could create a REST API, and the web app consuming it, in one project.
142
+
143
+ However, to avoid possible conflicts between the API resources and the web app routes you might want to add an `apiPrefix` to the REST API:
144
+
145
+ ### REST URIs prefixes
146
+
147
+ With the `apiPrefix` config setting, all REST resources get an extra path segment in front of them. If the `apiPrefix` is `'api'`, then `/movies/12345` becomes `/api/movies/12345`:
148
+
149
+ ```js
150
+ const config = { apiPrefix: 'api' }
151
+ const server = temba.create(config)
152
+ ```
153
+
154
+ After configuring the `apiPrefix`, requests to the root URL will either return a `404 Not Found` or a `405 Method Not Allowed`, depending on the HTTP method.
155
+
156
+ If you have configured both an `apiPrefix` and a `staticFolder`, a `GET` on the root URL will return the `index.html` in the `staticFolder`, if there is one.
157
+
158
+ ### Request body validation or mutation
159
+
160
+ Temba does not validate request bodies.
161
+
162
+ This means you can store your resources in any format you like. So creating the following two (very different) _movies_ is perfectly fine:
163
+
164
+ ```
165
+ POST /movies
166
+ {
167
+ "title": "O Brother, Where Art Thou?",
168
+ "description": "In the deep south during the 1930s, three escaped convicts search for hidden treasure while a relentless lawman pursues them."
169
+ }
170
+
171
+ POST /movies
172
+ {
173
+ "foo": "bar",
174
+ "baz": "boo"
175
+ }
176
+ ```
177
+
178
+ You can even omit a request body when doing a `POST` or `PUT`. If you don't want that, and build proper validation, use the `requestBodyValidator` config setting:
179
+
180
+ If you want to do input validation before the `POST` or `PUT` request body is saved to the database, configure Temba as follows:
181
+
182
+ ```js
183
+ const config = {
184
+ requestBodyValidator: {
185
+ post: (resourceName, requestBody) => {
186
+ // Validate, or even change the requestBody
187
+ },
188
+ put: (resourceName, requestBody) => {
189
+ // Validate, or even change the requestBody
190
+ },
191
+ },
192
+ }
193
+
194
+ const server = temba.create(config)
195
+ ```
196
+
197
+ The `requestBodyValidator` is an object with a `post` and/or `put` field, which contains the callback function you want Temba to call before the JSON is saved to the database.
198
+
199
+ The callback function receives two arguments: The `resourceName`, which for example is `movies` if you request `POST /movies`. The second argument is the `requestBody`, which is the JSON object in the request body.
200
+
201
+ Your callback function can return the following things:
202
+
203
+ - `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.
204
+ - `string`: If you return a string Temba will return a `400 Bad Request` with the string as error message.
205
+ - `object`: Return an object if you want to change the request body. Temba will save the returned object instead of the original request body.
206
+
207
+ Example:
208
+
209
+ ```js
210
+ const config = {
211
+ requestBodyValidator: {
212
+ post: (resourceName, requestBody) => {
213
+ // Do not allow Pokemons to be created: 400 Bad Request
214
+ if (resourceName === 'pokemons')
215
+ return 'You are not allowed to create new Pokemons'
216
+
217
+ // Add a genre to Star Trek films:
218
+ if (
219
+ resourceName === 'movies' &&
220
+ requestBody.title.startsWith('Star Trek')
221
+ )
222
+ return { ...requestBody, genre: 'Science Fiction' }
223
+
224
+ // If you end up here, void will be returned, so the request will just be saved.
225
+ },
226
+ },
227
+ }
228
+
229
+ const server = temba.create(config)
230
+ ```
231
+
232
+ ### Config settings overview
233
+
234
+ Configuring Temba is optional, it already works out of the box.
235
+
236
+ Here is an example of the config settings for Temba, and how you define them:
237
+
238
+ ```js
239
+ const config = {
240
+ resourceNames: ['movies', 'actors'],
241
+ connectionString: 'mongodb://localhost:27017',
242
+ staticFolder: 'build',
243
+ apiPrefix: 'api',
244
+ cacheControl: 'public, max-age=300',
245
+ delay: 500,
246
+ requestBodyValidator: {
247
+ post: (resourceName, requestBody) => {
248
+ // Validate, or even change the requestBody
249
+ },
250
+ put: (resourceName, requestBody) => {
251
+ // Validate, or even change the requestBody
252
+ },
253
+ },
254
+ }
255
+ const server = temba.create(config)
256
+ ```
257
+
258
+ None of the settings are required, and none of them have default values that actually do something. So only the settings you define are used.
259
+
260
+ These are all the possible settings:
261
+
262
+ | Config setting | Description |
263
+ | :--------------------- | :----------------------------------------------------------------------------------------- |
264
+ | `resourceNames` | See [Allowing specific resources only](#allowing-specific-resources-only) |
265
+ | `connectionString` | See [MongoDB](#mongodb) |
266
+ | `staticFolder` | See [Static assets](#static-assets) |
267
+ | `apiPrefix` | See [REST URIs prefixes](#rest-uris-prefixes) |
268
+ | `cacheControl` | The `Cache-control` response header value for each GET request. |
269
+ | `delay` | After processing the request, the delay in milliseconds before the request should be sent. |
270
+ | `requestBodyValidator` | See [Request body validation or mutation](#request-body-validation-or-mutation) |
271
+
272
+ ## Not supported (yet?)
273
+
274
+ The following features would be very nice for Temba to support:
275
+
276
+ ### `PATCH` requests
277
+
278
+ Partial updates using `PATCH`, or other HTTP methods are not (yet?) supported.
279
+
280
+ ### Auth
281
+
282
+ Temba offers no ways for authentication or authorization (yet?), so if someone knows how to reach the API, they can read and mutate all your data, unless you restrict this in another way.
283
+
284
+ ### Nested parent-child resources
285
+
286
+ Also nested (parent-child) routes are not supported (yet?), so every URI has the /:resource/:id structure and there is no way to indicate any relation, apart from within the JSON itself perhaps.
287
+
288
+ ### Filtering and sorting
289
+
290
+ And there is no filtering, sorting, searching, etc. (yet?).
291
+
292
+ ## Under the hood
293
+
294
+ Temba is built with JavaScript, [Node](https://nodejs.org), [Express](https://expressjs.com/), [Jest](https://jestjs.io/), [Testing Library](https://testing-library.com/), [Supertest](https://www.npmjs.com/package/supertest), and [@rakered/mongo](https://www.npmjs.com/package/@rakered/mongo).
295
+
296
+ ## Which problem does Temba solve?
297
+
298
+ The problem with JSON file solutions like json-server is the limitations you have when hosting your app, because your data is stored in a file.
299
+
300
+ For example, hosting json-server on GitHub Pages means your API is essentially readonly, because, although mutations are supported, your data is not really persisted.
301
+
302
+ And hosting json-server on Heroku does give you persistence, but is not reliable because of its [ephemeral filesystem](https://devcenter.heroku.com/articles/dynos#ephemeral-filesystem).
303
+
304
+ These limitations are of course the whole idea behind json-server, it's for simple mocking and prototyping. But if you want more (persistence wise) and don't mind having a database, you might want to try Temba.
305
+
306
+ ## Contributors ✨
307
+
308
+ Thanks goes to these wonderful people ([emoji key](https://allcontributors.org/docs/en/emoji-key)):
309
+
310
+ <!-- ALL-CONTRIBUTORS-LIST:START - Do not remove or modify this section -->
311
+ <!-- prettier-ignore-start -->
312
+ <!-- markdownlint-disable -->
313
+ <table>
314
+ <tr>
315
+ <td align="center"><a href="https://bouwe.io"><img src="https://avatars.githubusercontent.com/u/4126793?v=4?s=100" width="100px;" alt=""/><br /><sub><b>Bouwe K. Westerdijk</b></sub></a><br /><a href="https://github.com/bouwe77/temba/commits?author=bouwe77" title="Code">💻</a> <a href="https://github.com/bouwe77/temba/issues?q=author%3Abouwe77" title="Bug reports">🐛</a> <a href="https://github.com/bouwe77/temba/commits?author=bouwe77" title="Documentation">📖</a> <a href="#ideas-bouwe77" title="Ideas, Planning, & Feedback">🤔</a> <a href="https://github.com/bouwe77/temba/commits?author=bouwe77" title="Tests">⚠️</a></td>
316
+ </tr>
317
+ </table>
318
+
319
+ <!-- markdownlint-restore -->
320
+ <!-- prettier-ignore-end -->
321
+
322
+ <!-- ALL-CONTRIBUTORS-LIST:END -->
323
+
324
+ This project follows the [all-contributors](https://github.com/all-contributors/all-contributors) specification. Contributions of any kind welcome!
@@ -1,78 +1,62 @@
1
1
  "use strict";
2
-
3
- var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
4
-
5
- Object.defineProperty(exports, "__esModule", {
6
- value: true
7
- });
8
- exports.initConfig = initConfig;
9
-
10
- var _defineProperty2 = _interopRequireDefault(require("@babel/runtime/helpers/defineProperty"));
11
-
12
- var _logging = require("../logging");
13
-
14
- function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) { symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); } keys.push.apply(keys, symbols); } return keys; }
15
-
16
- function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(Object(source), true).forEach(function (key) { (0, _defineProperty2["default"])(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; }
17
-
18
- var defaultConfig = {
19
- resourceNames: [],
20
- validateResources: false,
21
- logLevel: _logging.logLevels.DEBUG,
22
- staticFolder: null,
23
- apiPrefix: '',
24
- connectionString: null,
25
- cacheControl: 'no-store',
26
- delay: 0,
27
- requestBodyValidator: {
28
- post: function post() {},
29
- put: function put() {}
30
- }
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.initConfig = void 0;
4
+ const defaultConfig = {
5
+ resourceNames: [],
6
+ validateResources: false,
7
+ staticFolder: null,
8
+ apiPrefix: '',
9
+ connectionString: null,
10
+ cacheControl: 'no-store',
11
+ delay: 0,
12
+ requestBodyValidator: {
13
+ post: () => {
14
+ // do nothing
15
+ },
16
+ put: () => {
17
+ // do nothing
18
+ },
19
+ },
31
20
  };
32
-
33
21
  function initConfig(userConfig) {
34
- if (!userConfig) return defaultConfig;
35
-
36
- var config = _objectSpread({}, defaultConfig);
37
-
38
- if (userConfig.resourceNames && userConfig.resourceNames.length > 0) {
39
- config.resourceNames = userConfig.resourceNames;
40
- config.validateResources = true;
41
- }
42
-
43
- if (userConfig.logLevel && userConfig.logLevel.length !== 0 && Object.keys(_logging.logLevels).includes(userConfig.logLevel.toUpperCase())) {
44
- config.logLevel = userConfig.logLevel.toUpperCase();
45
- }
46
-
47
- if (userConfig.staticFolder) {
48
- config.staticFolder = userConfig.staticFolder.replace(/[^a-zA-Z0-9]/g, '');
49
- }
50
-
51
- if (userConfig.apiPrefix) {
52
- config.apiPrefix = '/' + userConfig.apiPrefix.replace(/[^a-zA-Z0-9]/g, '') + '/';
53
- }
54
-
55
- if (userConfig.connectionString && userConfig.connectionString.length > 0) {
56
- config.connectionString = userConfig.connectionString;
57
- }
58
-
59
- if (userConfig.cacheControl && userConfig.cacheControl.length > 0) {
60
- config.cacheControl = userConfig.cacheControl;
61
- }
62
-
63
- if (userConfig.delay && userConfig.delay.length !== 0 && typeof Number(userConfig.delay) === 'number' && Number(userConfig.delay) > 0 && Number(userConfig.delay) < 10000) {
64
- config.delay = Number(userConfig.delay);
65
- }
66
-
67
- if (userConfig.requestBodyValidator) {
68
- if (userConfig.requestBodyValidator.post && typeof userConfig.requestBodyValidator.post === 'function') {
69
- config.requestBodyValidator.post = userConfig.requestBodyValidator.post;
22
+ if (!userConfig)
23
+ return defaultConfig;
24
+ const config = Object.assign({}, defaultConfig);
25
+ if (userConfig.resourceNames && userConfig.resourceNames.length > 0) {
26
+ config.resourceNames = userConfig.resourceNames;
27
+ config.validateResources = true;
28
+ }
29
+ if (userConfig.staticFolder) {
30
+ config.staticFolder = userConfig.staticFolder.replace(/[^a-zA-Z0-9]/g, '');
31
+ }
32
+ if (userConfig.apiPrefix) {
33
+ config.apiPrefix =
34
+ '/' + userConfig.apiPrefix.replace(/[^a-zA-Z0-9]/g, '') + '/';
35
+ }
36
+ if (userConfig.connectionString && userConfig.connectionString.length > 0) {
37
+ config.connectionString = userConfig.connectionString;
70
38
  }
71
-
72
- if (userConfig.requestBodyValidator.put && typeof userConfig.requestBodyValidator.put === 'function') {
73
- config.requestBodyValidator.put = userConfig.requestBodyValidator.put;
39
+ if (userConfig.cacheControl && userConfig.cacheControl.length > 0) {
40
+ config.cacheControl = userConfig.cacheControl;
74
41
  }
75
- }
76
-
77
- return config;
78
- }
42
+ if (userConfig.delay &&
43
+ userConfig.delay !== 0 &&
44
+ typeof Number(userConfig.delay) === 'number' &&
45
+ Number(userConfig.delay) > 0 &&
46
+ Number(userConfig.delay) < 10000) {
47
+ config.delay = Number(userConfig.delay);
48
+ }
49
+ if (userConfig.requestBodyValidator) {
50
+ if (userConfig.requestBodyValidator.post &&
51
+ typeof userConfig.requestBodyValidator.post === 'function') {
52
+ config.requestBodyValidator.post = userConfig.requestBodyValidator.post;
53
+ }
54
+ if (userConfig.requestBodyValidator.put &&
55
+ typeof userConfig.requestBodyValidator.put === 'function') {
56
+ config.requestBodyValidator.put = userConfig.requestBodyValidator.put;
57
+ }
58
+ }
59
+ return config;
60
+ }
61
+ exports.initConfig = initConfig;
62
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/config/index.ts"],"names":[],"mappings":";;;AAaA,MAAM,aAAa,GAAW;IAC5B,aAAa,EAAE,EAAE;IACjB,iBAAiB,EAAE,KAAK;IACxB,YAAY,EAAE,IAAI;IAClB,SAAS,EAAE,EAAE;IACb,gBAAgB,EAAE,IAAI;IACtB,YAAY,EAAE,UAAU;IACxB,KAAK,EAAE,CAAC;IACR,oBAAoB,EAAE;QACpB,IAAI,EAAE,GAAG,EAAE;YACT,aAAa;QACf,CAAC;QACD,GAAG,EAAE,GAAG,EAAE;YACR,aAAa;QACf,CAAC;KACF;CACF,CAAA;AAED,SAAgB,UAAU,CAAC,UAAkB;IAC3C,IAAI,CAAC,UAAU;QAAE,OAAO,aAAa,CAAA;IAErC,MAAM,MAAM,qBAAQ,aAAa,CAAE,CAAA;IAEnC,IAAI,UAAU,CAAC,aAAa,IAAI,UAAU,CAAC,aAAa,CAAC,MAAM,GAAG,CAAC,EAAE;QACnE,MAAM,CAAC,aAAa,GAAG,UAAU,CAAC,aAAa,CAAA;QAC/C,MAAM,CAAC,iBAAiB,GAAG,IAAI,CAAA;KAChC;IAED,IAAI,UAAU,CAAC,YAAY,EAAE;QAC3B,MAAM,CAAC,YAAY,GAAG,UAAU,CAAC,YAAY,CAAC,OAAO,CAAC,eAAe,EAAE,EAAE,CAAC,CAAA;KAC3E;IAED,IAAI,UAAU,CAAC,SAAS,EAAE;QACxB,MAAM,CAAC,SAAS;YACd,GAAG,GAAG,UAAU,CAAC,SAAS,CAAC,OAAO,CAAC,eAAe,EAAE,EAAE,CAAC,GAAG,GAAG,CAAA;KAChE;IAED,IAAI,UAAU,CAAC,gBAAgB,IAAI,UAAU,CAAC,gBAAgB,CAAC,MAAM,GAAG,CAAC,EAAE;QACzE,MAAM,CAAC,gBAAgB,GAAG,UAAU,CAAC,gBAAgB,CAAA;KACtD;IAED,IAAI,UAAU,CAAC,YAAY,IAAI,UAAU,CAAC,YAAY,CAAC,MAAM,GAAG,CAAC,EAAE;QACjE,MAAM,CAAC,YAAY,GAAG,UAAU,CAAC,YAAY,CAAA;KAC9C;IAED,IACE,UAAU,CAAC,KAAK;QAChB,UAAU,CAAC,KAAK,KAAK,CAAC;QACtB,OAAO,MAAM,CAAC,UAAU,CAAC,KAAK,CAAC,KAAK,QAAQ;QAC5C,MAAM,CAAC,UAAU,CAAC,KAAK,CAAC,GAAG,CAAC;QAC5B,MAAM,CAAC,UAAU,CAAC,KAAK,CAAC,GAAG,KAAK,EAChC;QACA,MAAM,CAAC,KAAK,GAAG,MAAM,CAAC,UAAU,CAAC,KAAK,CAAC,CAAA;KACxC;IAED,IAAI,UAAU,CAAC,oBAAoB,EAAE;QACnC,IACE,UAAU,CAAC,oBAAoB,CAAC,IAAI;YACpC,OAAO,UAAU,CAAC,oBAAoB,CAAC,IAAI,KAAK,UAAU,EAC1D;YACA,MAAM,CAAC,oBAAoB,CAAC,IAAI,GAAG,UAAU,CAAC,oBAAoB,CAAC,IAAI,CAAA;SACxE;QACD,IACE,UAAU,CAAC,oBAAoB,CAAC,GAAG;YACnC,OAAO,UAAU,CAAC,oBAAoB,CAAC,GAAG,KAAK,UAAU,EACzD;YACA,MAAM,CAAC,oBAAoB,CAAC,GAAG,GAAG,UAAU,CAAC,oBAAoB,CAAC,GAAG,CAAA;SACtE;KACF;IAED,OAAO,MAAM,CAAA;AACf,CAAC;AArDD,gCAqDC"}
@@ -0,0 +1,16 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.createDelayMiddleware = void 0;
7
+ const connect_pause_1 = __importDefault(require("connect-pause"));
8
+ function createDelayMiddleware(delay) {
9
+ return function (req, res, next) {
10
+ console.log('Start delay...');
11
+ (0, connect_pause_1.default)(delay)(req, res, next);
12
+ console.log('Delay finished!');
13
+ };
14
+ }
15
+ exports.createDelayMiddleware = createDelayMiddleware;
16
+ //# sourceMappingURL=delayMiddleware.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"delayMiddleware.js","sourceRoot":"","sources":["../../src/delay/delayMiddleware.ts"],"names":[],"mappings":";;;;;;AAAA,kEAAiC;AAEjC,SAAS,qBAAqB,CAAC,KAAK;IAClC,OAAO,UAAU,GAAG,EAAE,GAAG,EAAE,IAAI;QAC7B,OAAO,CAAC,GAAG,CAAC,gBAAgB,CAAC,CAAA;QAC7B,IAAA,uBAAK,EAAC,KAAK,CAAC,CAAC,GAAG,EAAE,GAAG,EAAE,IAAI,CAAC,CAAA;QAC5B,OAAO,CAAC,GAAG,CAAC,iBAAiB,CAAC,CAAA;IAChC,CAAC,CAAA;AACH,CAAC;AAEQ,sDAAqB"}
@@ -0,0 +1,34 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.new500InternalServerError = exports.new400BadRequestError = exports.new404NotFoundError = exports.errorHandler = exports.HttpError = void 0;
4
+ class HttpError extends Error {
5
+ constructor(status, message) {
6
+ super(message);
7
+ this.status = status;
8
+ this.message = message;
9
+ }
10
+ }
11
+ exports.HttpError = HttpError;
12
+ // This is the error middleware that will be used by the server.
13
+ function errorHandler(e, _, res) {
14
+ const status = 500;
15
+ let message = 'Unknown error';
16
+ if (e instanceof Error) {
17
+ message = e.message;
18
+ }
19
+ return res.status(status).json({ message });
20
+ }
21
+ exports.errorHandler = errorHandler;
22
+ function new404NotFoundError(message = 'Not Found') {
23
+ return new HttpError(404, message);
24
+ }
25
+ exports.new404NotFoundError = new404NotFoundError;
26
+ function new400BadRequestError(message = 'Bad Request') {
27
+ return new HttpError(400, message);
28
+ }
29
+ exports.new400BadRequestError = new400BadRequestError;
30
+ function new500InternalServerError(message = 'Internal Server Error') {
31
+ return new HttpError(500, message);
32
+ }
33
+ exports.new500InternalServerError = new500InternalServerError;
34
+ //# sourceMappingURL=errors.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"errors.js","sourceRoot":"","sources":["../../src/errors/errors.ts"],"names":[],"mappings":";;;AAAA,MAAa,SAAU,SAAQ,KAAK;IAIlC,YAAY,MAAc,EAAE,OAAe;QACzC,KAAK,CAAC,OAAO,CAAC,CAAA;QAEd,IAAI,CAAC,MAAM,GAAG,MAAM,CAAA;QACpB,IAAI,CAAC,OAAO,GAAG,OAAO,CAAA;IACxB,CAAC;CACF;AAVD,8BAUC;AAED,gEAAgE;AAChE,SAAS,YAAY,CAAC,CAAU,EAAE,CAAC,EAAE,GAAG;IACtC,MAAM,MAAM,GAAG,GAAG,CAAA;IAClB,IAAI,OAAO,GAAG,eAAe,CAAA;IAE7B,IAAI,CAAC,YAAY,KAAK,EAAE;QACtB,OAAO,GAAG,CAAC,CAAC,OAAO,CAAA;KACpB;IAED,OAAO,GAAG,CAAC,MAAM,CAAC,MAAM,CAAC,CAAC,IAAI,CAAC,EAAE,OAAO,EAAE,CAAC,CAAA;AAC7C,CAAC;AAeC,oCAAY;AAbd,SAAS,mBAAmB,CAAC,OAAO,GAAG,WAAW;IAChD,OAAO,IAAI,SAAS,CAAC,GAAG,EAAE,OAAO,CAAC,CAAA;AACpC,CAAC;AAYC,kDAAmB;AAVrB,SAAS,qBAAqB,CAAC,OAAO,GAAG,aAAa;IACpD,OAAO,IAAI,SAAS,CAAC,GAAG,EAAE,OAAO,CAAC,CAAA;AACpC,CAAC;AASC,sDAAqB;AAPvB,SAAS,yBAAyB,CAAC,OAAO,GAAG,uBAAuB;IAClE,OAAO,IAAI,SAAS,CAAC,GAAG,EAAE,OAAO,CAAC,CAAA;AACpC,CAAC;AAMC,8DAAyB"}
@@ -0,0 +1,46 @@
1
+ {
2
+ "name": "temba",
3
+ "version": "0.10.2",
4
+ "description": "Get a simple MongoDB REST API with zero coding in less than 30 seconds (seriously).",
5
+ "main": "dist/server.ts",
6
+ "scripts": {
7
+ "build": "rm -rf dist && tsc && cp package.json README.md ./dist",
8
+ "test": "jest --watch",
9
+ "lint": "eslint --ignore-path .gitignore --ext .js,.ts .",
10
+ "format": "prettier --ignore-path .gitignore --write \"**/*.+(js|ts|json)\""
11
+ },
12
+ "repository": {
13
+ "type": "git",
14
+ "url": "https://github.com/bouwe77/temba.git"
15
+ },
16
+ "homepage": "https://github.com/bouwe77/temba#readme",
17
+ "author": "Bouwe (https://bouwe.io)",
18
+ "license": "ISC",
19
+ "files": [
20
+ "dist/**"
21
+ ],
22
+ "devDependencies": {
23
+ "@types/cors": "^2.8.12",
24
+ "@types/express": "^4.17.13",
25
+ "@types/jest": "^27.4.0",
26
+ "@types/morgan": "^1.9.3",
27
+ "@types/supertest": "^2.0.11",
28
+ "@typescript-eslint/eslint-plugin": "^5.10.0",
29
+ "@typescript-eslint/parser": "^5.10.0",
30
+ "eslint": "^8.7.0",
31
+ "eslint-config-prettier": "^8.3.0",
32
+ "jest": "^27.4.7",
33
+ "jest-extended": "^0.11.5",
34
+ "prettier": "^2.5.1",
35
+ "supertest": "^6.2.2",
36
+ "ts-jest": "^27.1.3",
37
+ "typescript": "^4.5.5"
38
+ },
39
+ "dependencies": {
40
+ "@rakered/mongo": "^1.6.0",
41
+ "connect-pause": "^0.1.0",
42
+ "cors": "^2.8.5",
43
+ "express": "^4.17.1",
44
+ "morgan": "^1.10.0"
45
+ }
46
+ }