Skip to content

Commit 283a491

Browse files
Ethan-Arrowoodcb1kenobi
authored andcommitted
document server global object (#145)
* stub out and start documenting server object * complete draft * Update docs/technical-details/reference/globals.md Co-authored-by: Chris Barber <[email protected]> --------- Co-authored-by: Chris Barber <[email protected]>
1 parent e7aff7f commit 283a491

File tree

1 file changed

+165
-9
lines changed

1 file changed

+165
-9
lines changed

docs/technical-details/reference/globals.md

Lines changed: 165 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -22,7 +22,7 @@ const { tables, Resource } = require('harperdb');
2222

2323
The global variables include:
2424

25-
### `tables`
25+
## `tables`
2626

2727
This is an object that holds all the tables for the default database (called `data`) as properties. Each of these property values is a table class that subclasses the Resource interface and provides access to the table through the Resource interface. For example, you can get a record from a table (in the default database) called 'my-table' with:
2828

@@ -36,7 +36,7 @@ async function getRecord() {
3636

3737
It is recommended that you [define a database](../../getting-started/getting-started.md) for all the tables that are required to exist in your application. This will ensure that the tables exist on the `tables` object. Also note that the property names follow a CamelCase convention for use in JavaScript and in the GraphQL Schemas, but these are translated to snake\_case for the actual table names, and converted back to CamelCase when added to the `tables` object.
3838

39-
### `databases`
39+
## `databases`
4040

4141
This is an object that holds all the databases in HarperDB, and can be used to explicitly access a table by database name. Each database will be a property on this object, each of these property values will be an object with the set of all tables in that database. The default database, `databases.data` should equal the `tables` export. For example, if you want to access the "dog" table in the "dev" database, you could do so:
4242

@@ -45,27 +45,183 @@ import { databases } from 'harperdb';
4545
const { Dog } = databases.dev;
4646
```
4747

48-
### `Resource`
48+
## `Resource`
4949

5050
This is the base class for all resources, including tables and external data sources. This is provided so that you can extend it to implement custom data source providers. See the [Resource API documentation](resource.md) for more details about implementing a Resource class.
5151

52-
### `auth(username, password?): Promise<User>`
52+
## `auth(username, password?): Promise<User>`
5353

5454
This returns the user object with permissions/authorization information based on the provided username. If a password is provided, the password will be verified before returning the user object (if the password is incorrect, an error will be thrown).
5555

56-
### `logger`
56+
## `logger`
5757

5858
This provides methods `trace`, `debug`, `info`, `warn`, `error`, `fatal`, and `notify` for logging. See the [logging documentation](../../administration/logging/logging.md) for more information.
5959

60-
### `server`
60+
## `server`
6161

62-
This provides a number of functions and objects to interact with the server including:
62+
The `server` global object provides a number of functions and objects to interact with Harper's HTTP service.
6363

64-
#### `server.config`
64+
### `server.http(listener: RequestListener, options: HttpOptions): HttpServer[]`
65+
66+
Alias: `server.request`
67+
68+
Add a handler method to the HTTP server request listener middleware chain.
69+
70+
Returns an array of server instances based on the specified `options.port` and `options.securePort`.
71+
72+
Example:
73+
74+
```js
75+
server.http((request, next) => {
76+
return request.url === '/graphql'
77+
? handleGraphQLRequest(request)
78+
: next(request);
79+
}, {
80+
runFirst: true, // run this handler first
81+
});
82+
```
83+
84+
#### `RequestListener`
85+
86+
Type: `(request: Request, next: RequestListener) => Promise<Response>`
87+
88+
The HTTP request listener to be added to the middleware chain. To continue chain execution pass the `request` to the `next` function such as `return next(request);`.
89+
90+
#### `Request`
91+
92+
An implementation of WHATWG [Request](https://developer.mozilla.org/en-US/docs/Web/API/Request) class.
93+
94+
#### `Response`
95+
96+
An implementation of WHATWG [Response](https://developer.mozilla.org/en-US/docs/Web/API/Response) class.
97+
98+
#### `HttpOptions`
99+
100+
Type: `Object`
101+
102+
Properties:
103+
104+
<!-- Internal Use Only - `mtls` - _optional_ - `boolean` -->
105+
<!-- Internal Use Only - `isOperationsServer` - _optional_ - `boolean` -->
106+
- `runFirst` - _optional_ - `boolean` - Add listener to the front of the middleware chain. Defaults to `false`
107+
- `port` - _optional_ - `number` - Specify which HTTP server middleware chain to add the listener to. Defaults to the Harper system default HTTP port configured by `harperdb-config.yaml`, generally `9926`
108+
- `securePort` - _optional_ - `number` - Specify which HTTPS server middleware chain to add the listener to. Defaults to the Harper system default HTTP secure port configured by `harperdb-config.yaml`, generally `9927`
109+
110+
#### `HttpServer`
111+
112+
Node.js [`http.Server`](https://nodejs.org/api/http.html#class-httpserver) or [`https.SecureServer`](https://nodejs.org/api/https.html#class-httpsserver) instance.
113+
114+
### `server.socket(listener: ConnectionListener, options: SocketOptions): SocketServer`
115+
116+
Creates a socket server on the specified `options.port` or `options.securePort`.
117+
118+
Only one socket server will be created. A `securePort` takes precedence.
119+
120+
#### `ConnectionListener`
121+
122+
Node.js socket server connection listener as documented in [`net.createServer`](https://nodejs.org/api/net.html#netcreateserveroptions-connectionlistener) or [`tls.createServer`](https://nodejs.org/api/tls.html#tlscreateserveroptions-secureconnectionlistener)
123+
124+
#### `SocketOptions`
125+
126+
- `port` - _optional_ - `number` - Specify the port for the [`net.Server`](https://nodejs.org/api/net.html#class-netserver) instance.
127+
- `securePort` - _optional_ - `number` - Specify the port for the [`tls.Server`](https://nodejs.org/api/tls.html#class-tlsserver) instance.
128+
129+
#### `SocketServer`
130+
131+
Node.js [`net.Server`](https://nodejs.org/api/net.html#class-netserver) or [`tls.Server`](https://nodejs.org/api/tls.html#class-tlsserver) instance.
132+
133+
### `server.ws(listener: WsListener, options: WsOptions): HttpServer[]`
134+
135+
Add a listener to the WebSocket connection listener middleware chain. The WebSocket server is associated with the HTTP server specified by the `options.port` or `options.securePort`. Use the [`server.upgrade()`](#serverupgradelistener-upgradelistener-options-upgradeoptions-void) method to add a listener to the upgrade middleware chain.
136+
137+
Example:
138+
139+
```js
140+
server.ws((ws, request, chainCompletion) => {
141+
chainCompletion.then(() => {
142+
ws.on('error', console.error);
143+
144+
ws.on('message', function message(data) {
145+
console.log('received: %s', data);
146+
});
147+
148+
ws.send('something');
149+
});
150+
});
151+
```
152+
153+
#### `WsListener`
154+
155+
Type: `(ws: WebSocket, request: Request, chainCompletion: ChainCompletion, next: WsListener): Promise<void>`
156+
157+
The WebSocket connection listener.
158+
159+
- The `ws` argument is the [WebSocket](https://github.com/websockets/ws/blob/master/doc/ws.md#class-websocket) instance as defined by the `ws` module.
160+
- The `request` argument is Harper's transformation of the `IncomingMessage` argument of the standard ['connection'](https://github.com/websockets/ws/blob/master/doc/ws.md#event-connection) listener event for a WebSocket server.
161+
- The `chainCompletion` argument is a `Promise` of the associated HTTP server's request chain. Awaiting this promise enables the user to ensure the HTTP request has finished being processed before operating on the WebSocket.
162+
- The `next` argument is similar to that of other `next` arguments in Harper's server middlewares. To continue execution of the WebSocket connection listener middleware chain, pass all of the other arguments to this one such as: `next(ws, request, chainCompletion)`
163+
164+
#### `WsOptions`
165+
166+
Type: `Object`
167+
168+
Properties:
169+
170+
<!-- Internal Use Only - `mtls` - _optional_ - `boolean` -->
171+
<!-- Internal Use Only - `isOperationsServer` - _optional_ - `boolean` -->
172+
- `maxPayload` - _optional_ - `number` - Set the max payload size for the WebSocket server. Defaults to 100 MB.
173+
- `runFirst` - _optional_ - `boolean` - Add listener to the front of the middleware chain. Defaults to `false`
174+
- `port` - _optional_ - `number` - Specify which WebSocket server middleware chain to add the listener to. Defaults to the Harper system default HTTP port configured by `harperdb-config.yaml`, generally `9926`
175+
- `securePort` - _optional_ - `number` - Specify which WebSocket secure server middleware chain to add the listener to. Defaults to the Harper system default HTTP secure port configured by `harperdb-config.yaml`, generally `9927`
176+
177+
### `server.upgrade(listener: UpgradeListener, options: UpgradeOptions): void`
178+
179+
Add a listener to the HTTP Server [upgrade](https://nodejs.org/api/http.html#event-upgrade_1) event. If a WebSocket connection listener is added using [`server.ws()`](#serverwslistener-wslistener-options-wsoptions-httpserver), a default upgrade handler will be added as well. The default upgrade handler will add a `__harperdb_request_upgraded` boolean to the `request` argument to signal the connection has already been upgraded. It will also check for this boolean _before_ upgrading and if it is `true`, it will pass the arguments along to the `next` listener.
180+
181+
This method should be used to delegate HTTP upgrade events to an external WebSocket server instance.
182+
183+
Example:
184+
185+
> This example is from the HarperDB Next.js component. See the complete source code [here](https://github.com/HarperDB/nextjs/blob/main/extension.js)
186+
187+
```js
188+
server.upgrade(
189+
(request, socket, head, next) => {
190+
if (request.url === '/_next/webpack-hmr') {
191+
return upgradeHandler(request, socket, head).then(() => {
192+
request.__harperdb_request_upgraded = true;
193+
194+
next(request, socket, head);
195+
});
196+
}
197+
198+
return next(request, socket, head);
199+
},
200+
{ runFirst: true }
201+
);
202+
```
203+
204+
#### `UpgradeListener`
205+
206+
Type: `(request, socket, head, next) => void`
207+
208+
The arguments are passed to the middleware chain from the HTTP server [`'upgrade'`](https://nodejs.org/api/http.html#event-upgrade_1) event.
209+
210+
#### `UpgradeOptions`
211+
212+
Type: `Object`
213+
214+
Properties:
215+
216+
- `runFirst` - _optional_ - `boolean` - Add listener to the front of the middleware chain. Defaults to `false`
217+
- `port` - _optional_ - `number` - Specify which HTTP server middleware chain to add the listener to. Defaults to the Harper system default HTTP port configured by `harperdb-config.yaml`, generally `9926`
218+
- `securePort` - _optional_ - `number` - Specify which HTTP secure server middleware chain to add the listener to. Defaults to the Harper system default HTTP secure port configured by `harperdb-config.yaml`, generally `9927`
219+
220+
### `server.config`
65221

66222
This provides access to the HarperDB configuration object. This comes from the [harperdb-config.yaml](../../deployments/configuration.md) (parsed into object form).
67223

68-
#### `server.recordAnalytics(value, metric, path?, method?, type?)`
224+
### `server.recordAnalytics(value, metric, path?, method?, type?)`
69225

70226
This records the provided value as a metric into HarperDB's analytics. HarperDB efficiently records and tracks these metrics and makes them available through [analytics API](analytics.md). The values are aggregated and statistical information is computed when many operations are performed. The optional parameters can be used to group statistics. For the parameters, make sure you are not grouping on too fine of a level for useful aggregation. The parameters are:
71227

0 commit comments

Comments
 (0)