@rest-vir/implement-service 0.0.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.
- package/LICENSE-CC0 +121 -0
- package/LICENSE-MIT +21 -0
- package/README.md +49 -0
- package/dist/implementation/generic-service-implementation.d.ts +44 -0
- package/dist/implementation/generic-service-implementation.js +1 -0
- package/dist/implementation/implement-endpoint.d.ts +113 -0
- package/dist/implementation/implement-endpoint.js +56 -0
- package/dist/implementation/implement-service.d.ts +91 -0
- package/dist/implementation/implement-service.js +63 -0
- package/dist/implementation/implement-web-socket.d.ts +67 -0
- package/dist/implementation/implement-web-socket.js +72 -0
- package/dist/implementation/service-context-init.d.ts +39 -0
- package/dist/implementation/service-context-init.js +1 -0
- package/dist/index.d.ts +9 -0
- package/dist/index.js +9 -0
- package/dist/util/data.d.ts +30 -0
- package/dist/util/data.js +1 -0
- package/dist/util/handler.error.d.ts +30 -0
- package/dist/util/handler.error.js +29 -0
- package/dist/util/service-logger.d.ts +52 -0
- package/dist/util/service-logger.js +43 -0
- package/package.json +64 -0
package/LICENSE-CC0
ADDED
|
@@ -0,0 +1,121 @@
|
|
|
1
|
+
CC0 1.0 Universal
|
|
2
|
+
|
|
3
|
+
Creative Commons Legal Code
|
|
4
|
+
|
|
5
|
+
CREATIVE COMMONS CORPORATION IS NOT A LAW FIRM AND DOES NOT PROVIDE
|
|
6
|
+
LEGAL SERVICES. DISTRIBUTION OF THIS DOCUMENT DOES NOT CREATE AN
|
|
7
|
+
ATTORNEY-CLIENT RELATIONSHIP. CREATIVE COMMONS PROVIDES THIS
|
|
8
|
+
INFORMATION ON AN "AS-IS" BASIS. CREATIVE COMMONS MAKES NO WARRANTIES
|
|
9
|
+
REGARDING THE USE OF THIS DOCUMENT OR THE INFORMATION OR WORKS
|
|
10
|
+
PROVIDED HEREUNDER, AND DISCLAIMS LIABILITY FOR DAMAGES RESULTING FROM
|
|
11
|
+
THE USE OF THIS DOCUMENT OR THE INFORMATION OR WORKS PROVIDED
|
|
12
|
+
HEREUNDER.
|
|
13
|
+
|
|
14
|
+
Statement of Purpose
|
|
15
|
+
|
|
16
|
+
The laws of most jurisdictions throughout the world automatically confer
|
|
17
|
+
exclusive Copyright and Related Rights (defined below) upon the creator
|
|
18
|
+
and subsequent owner(s) (each and all, an "owner") of an original work of
|
|
19
|
+
authorship and/or a database (each, a "Work").
|
|
20
|
+
|
|
21
|
+
Certain owners wish to permanently relinquish those rights to a Work for
|
|
22
|
+
the purpose of contributing to a commons of creative, cultural and
|
|
23
|
+
scientific works ("Commons") that the public can reliably and without fear
|
|
24
|
+
of later claims of infringement build upon, modify, incorporate in other
|
|
25
|
+
works, reuse and redistribute as freely as possible in any form whatsoever
|
|
26
|
+
and for any purposes, including without limitation commercial purposes.
|
|
27
|
+
These owners may contribute to the Commons to promote the ideal of a free
|
|
28
|
+
culture and the further production of creative, cultural and scientific
|
|
29
|
+
works, or to gain reputation or greater distribution for their Work in
|
|
30
|
+
part through the use and efforts of others.
|
|
31
|
+
|
|
32
|
+
For these and/or other purposes and motivations, and without any
|
|
33
|
+
expectation of additional consideration or compensation, the person
|
|
34
|
+
associating CC0 with a Work (the "Affirmer"), to the extent that he or she
|
|
35
|
+
is an owner of Copyright and Related Rights in the Work, voluntarily
|
|
36
|
+
elects to apply CC0 to the Work and publicly distribute the Work under its
|
|
37
|
+
terms, with knowledge of his or her Copyright and Related Rights in the
|
|
38
|
+
Work and the meaning and intended legal effect of CC0 on those rights.
|
|
39
|
+
|
|
40
|
+
1. Copyright and Related Rights. A Work made available under CC0 may be
|
|
41
|
+
protected by copyright and related or neighboring rights ("Copyright and
|
|
42
|
+
Related Rights"). Copyright and Related Rights include, but are not
|
|
43
|
+
limited to, the following:
|
|
44
|
+
|
|
45
|
+
i. the right to reproduce, adapt, distribute, perform, display,
|
|
46
|
+
communicate, and translate a Work;
|
|
47
|
+
ii. moral rights retained by the original author(s) and/or performer(s);
|
|
48
|
+
iii. publicity and privacy rights pertaining to a person's image or
|
|
49
|
+
likeness depicted in a Work;
|
|
50
|
+
iv. rights protecting against unfair competition in regards to a Work,
|
|
51
|
+
subject to the limitations in paragraph 4(a), below;
|
|
52
|
+
v. rights protecting the extraction, dissemination, use and reuse of data
|
|
53
|
+
in a Work;
|
|
54
|
+
vi. database rights (such as those arising under Directive 96/9/EC of the
|
|
55
|
+
European Parliament and of the Council of 11 March 1996 on the legal
|
|
56
|
+
protection of databases, and under any national implementation
|
|
57
|
+
thereof, including any amended or successor version of such
|
|
58
|
+
directive); and
|
|
59
|
+
vii. other similar, equivalent or corresponding rights throughout the
|
|
60
|
+
world based on applicable law or treaty, and any national
|
|
61
|
+
implementations thereof.
|
|
62
|
+
|
|
63
|
+
2. Waiver. To the greatest extent permitted by, but not in contravention
|
|
64
|
+
of, applicable law, Affirmer hereby overtly, fully, permanently,
|
|
65
|
+
irrevocably and unconditionally waives, abandons, and surrenders all of
|
|
66
|
+
Affirmer's Copyright and Related Rights and associated claims and causes
|
|
67
|
+
of action, whether now known or unknown (including existing as well as
|
|
68
|
+
future claims and causes of action), in the Work (i) in all territories
|
|
69
|
+
worldwide, (ii) for the maximum duration provided by applicable law or
|
|
70
|
+
treaty (including future time extensions), (iii) in any current or future
|
|
71
|
+
medium and for any number of copies, and (iv) for any purpose whatsoever,
|
|
72
|
+
including without limitation commercial, advertising or promotional
|
|
73
|
+
purposes (the "Waiver"). Affirmer makes the Waiver for the benefit of each
|
|
74
|
+
member of the public at large and to the detriment of Affirmer's heirs and
|
|
75
|
+
successors, fully intending that such Waiver shall not be subject to
|
|
76
|
+
revocation, rescission, cancellation, termination, or any other legal or
|
|
77
|
+
equitable action to disrupt the quiet enjoyment of the Work by the public
|
|
78
|
+
as contemplated by Affirmer's express Statement of Purpose.
|
|
79
|
+
|
|
80
|
+
3. Public License Fallback. Should any part of the Waiver for any reason
|
|
81
|
+
be judged legally invalid or ineffective under applicable law, then the
|
|
82
|
+
Waiver shall be preserved to the maximum extent permitted taking into
|
|
83
|
+
account Affirmer's express Statement of Purpose. In addition, to the
|
|
84
|
+
extent the Waiver is so judged Affirmer hereby grants to each affected
|
|
85
|
+
person a royalty-free, non transferable, non sublicensable, non exclusive,
|
|
86
|
+
irrevocable and unconditional license to exercise Affirmer's Copyright and
|
|
87
|
+
Related Rights in the Work (i) in all territories worldwide, (ii) for the
|
|
88
|
+
maximum duration provided by applicable law or treaty (including future
|
|
89
|
+
time extensions), (iii) in any current or future medium and for any number
|
|
90
|
+
of copies, and (iv) for any purpose whatsoever, including without
|
|
91
|
+
limitation commercial, advertising or promotional purposes (the
|
|
92
|
+
"License"). The License shall be deemed effective as of the date CC0 was
|
|
93
|
+
applied by Affirmer to the Work. Should any part of the License for any
|
|
94
|
+
reason be judged legally invalid or ineffective under applicable law, such
|
|
95
|
+
partial invalidity or ineffectiveness shall not invalidate the remainder
|
|
96
|
+
of the License, and in such case Affirmer hereby affirms that he or she
|
|
97
|
+
will not (i) exercise any of his or her remaining Copyright and Related
|
|
98
|
+
Rights in the Work or (ii) assert any associated claims and causes of
|
|
99
|
+
action with respect to the Work, in either case contrary to Affirmer's
|
|
100
|
+
express Statement of Purpose.
|
|
101
|
+
|
|
102
|
+
4. Limitations and Disclaimers.
|
|
103
|
+
|
|
104
|
+
a. No trademark or patent rights held by Affirmer are waived, abandoned,
|
|
105
|
+
surrendered, licensed or otherwise affected by this document.
|
|
106
|
+
b. Affirmer offers the Work as-is and makes no representations or
|
|
107
|
+
warranties of any kind concerning the Work, express, implied,
|
|
108
|
+
statutory or otherwise, including without limitation warranties of
|
|
109
|
+
title, merchantability, fitness for a particular purpose, non
|
|
110
|
+
infringement, or the absence of latent or other defects, accuracy, or
|
|
111
|
+
the present or absence of errors, whether or not discoverable, all to
|
|
112
|
+
the greatest extent permissible under applicable law.
|
|
113
|
+
c. Affirmer disclaims responsibility for clearing rights of other persons
|
|
114
|
+
that may apply to the Work or any use thereof, including without
|
|
115
|
+
limitation any person's Copyright and Related Rights in the Work.
|
|
116
|
+
Further, Affirmer disclaims responsibility for obtaining any necessary
|
|
117
|
+
consents, permissions or other rights required for any use of the
|
|
118
|
+
Work.
|
|
119
|
+
d. Affirmer understands and acknowledges that Creative Commons is not a
|
|
120
|
+
party to this document and has no duty or obligation with respect to
|
|
121
|
+
this CC0 or use of the Work.
|
package/LICENSE-MIT
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2024 electrovir
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
ADDED
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
# @rest-vir/implement-service
|
|
2
|
+
|
|
3
|
+
Part of the rest-vir suite. This package is used for implementing a REST service already defined by [`@rest-vir/define-service`](https://www.npmjs.com/package/@rest-vir/define-service).
|
|
4
|
+
|
|
5
|
+
See the full docs at https://electrovir.github.io/rest-vir
|
|
6
|
+
|
|
7
|
+
## Installation
|
|
8
|
+
|
|
9
|
+
```sh
|
|
10
|
+
npm i @rest-vir/implement-service
|
|
11
|
+
```
|
|
12
|
+
|
|
13
|
+
## Usage
|
|
14
|
+
|
|
15
|
+
Implement your service:
|
|
16
|
+
|
|
17
|
+
```TypeScript
|
|
18
|
+
import {HttpStatus, implementService} from '@rest-vir/implement-service';
|
|
19
|
+
|
|
20
|
+
export const myServiceImplementation = implementService(
|
|
21
|
+
{
|
|
22
|
+
service: myServiceDefinition,
|
|
23
|
+
},
|
|
24
|
+
{
|
|
25
|
+
endpoints: {
|
|
26
|
+
'/my-endpoint'() {
|
|
27
|
+
return {
|
|
28
|
+
statusCode: HttpStatus.Ok,
|
|
29
|
+
};
|
|
30
|
+
},
|
|
31
|
+
async '/my-endpoint/:user-id'({pathParams}) {
|
|
32
|
+
const user = await readUserFromDatabase(pathParams['user-id']);
|
|
33
|
+
|
|
34
|
+
return {
|
|
35
|
+
statusCode: HttpStatus.Ok,
|
|
36
|
+
responseData: user,
|
|
37
|
+
};
|
|
38
|
+
},
|
|
39
|
+
},
|
|
40
|
+
webSockets: {
|
|
41
|
+
'/my-web-socket': {
|
|
42
|
+
onMessage({webSocket}) {
|
|
43
|
+
webSocket.send('hi!');
|
|
44
|
+
},
|
|
45
|
+
},
|
|
46
|
+
},
|
|
47
|
+
},
|
|
48
|
+
);
|
|
49
|
+
```
|
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
import { type Overwrite } from '@augment-vir/common';
|
|
2
|
+
import { EndpointDefinition, EndpointPathBase, ServiceDefinition, WebSocketDefinition, type GenericEndpointDefinition, type GenericWebSocketDefinition, type NoParam } from '@rest-vir/define-service';
|
|
3
|
+
import { type ServiceLogger } from '../util/service-logger.js';
|
|
4
|
+
import { type EndpointImplementation } from './implement-endpoint.js';
|
|
5
|
+
import { type WebSocketImplementation } from './implement-web-socket.js';
|
|
6
|
+
import { type ContextInit } from './service-context-init.js';
|
|
7
|
+
/**
|
|
8
|
+
* A fully implemented endpoint.
|
|
9
|
+
*
|
|
10
|
+
* @category Internal
|
|
11
|
+
* @category Package : @rest-vir/implement-service
|
|
12
|
+
* @package [`@rest-vir/implement-service`](https://www.npmjs.com/package/@rest-vir/implement-service)
|
|
13
|
+
*/
|
|
14
|
+
export type ImplementedEndpoint<Context = any, ServiceName extends string = any, SpecificEndpoint extends EndpointDefinition = GenericEndpointDefinition> = Overwrite<SpecificEndpoint, {
|
|
15
|
+
service: GenericServiceImplementation;
|
|
16
|
+
}> & {
|
|
17
|
+
implementation: EndpointImplementation<Context, ServiceName>;
|
|
18
|
+
};
|
|
19
|
+
/**
|
|
20
|
+
* A super generic service implementation that be assigned to from any concrete service
|
|
21
|
+
* implementation.
|
|
22
|
+
*
|
|
23
|
+
* @category Internal
|
|
24
|
+
* @category Package : @rest-vir/implement-service
|
|
25
|
+
* @package [`@rest-vir/implement-service`](https://www.npmjs.com/package/@rest-vir/implement-service)
|
|
26
|
+
*/
|
|
27
|
+
export type GenericServiceImplementation = Omit<ServiceDefinition, 'endpoints' | 'webSockets'> & {
|
|
28
|
+
endpoints: Record<EndpointPathBase, any>;
|
|
29
|
+
webSockets: Record<EndpointPathBase, ImplementedWebSocket>;
|
|
30
|
+
createContext: ContextInit<any, any, any, any> | undefined;
|
|
31
|
+
logger: ServiceLogger;
|
|
32
|
+
};
|
|
33
|
+
/**
|
|
34
|
+
* A fully implemented WebSocket.
|
|
35
|
+
*
|
|
36
|
+
* @category Internal
|
|
37
|
+
* @category Package : @rest-vir/implement-service
|
|
38
|
+
* @package [`@rest-vir/implement-service`](https://www.npmjs.com/package/@rest-vir/implement-service)
|
|
39
|
+
*/
|
|
40
|
+
export type ImplementedWebSocket<Context = any, ServiceName extends string = any, SpecificWebSocket extends WebSocketDefinition | NoParam = NoParam> = Overwrite<SpecificWebSocket extends NoParam ? GenericWebSocketDefinition : SpecificWebSocket, {
|
|
41
|
+
service: GenericServiceImplementation;
|
|
42
|
+
}> & {
|
|
43
|
+
implementation: WebSocketImplementation<Context, ServiceName, SpecificWebSocket>;
|
|
44
|
+
};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export {};
|
|
@@ -0,0 +1,113 @@
|
|
|
1
|
+
import { ErrorHttpStatusCategories, ExtractKeysWithMatchingValues, HttpMethod, HttpStatusByCategory, MaybePromise, SuccessHttpStatusCategories } from '@augment-vir/common';
|
|
2
|
+
import { BaseSearchParams, BaseServiceEndpointsInit, EndpointDefinition, EndpointInit, EndpointPathBase, MinimalService, NoParam, ServiceDefinition, WithFinalEndpointProps, type PathParams } from '@rest-vir/define-service';
|
|
3
|
+
import { type IncomingHttpHeaders, type OutgoingHttpHeaders } from 'node:http';
|
|
4
|
+
import { type IsEqual, type IsNever } from 'type-fest';
|
|
5
|
+
import { ServerRequest, type ServerResponse } from '../util/data.js';
|
|
6
|
+
import { type ServiceLogger } from '../util/service-logger.js';
|
|
7
|
+
/**
|
|
8
|
+
* The part of {@link EndpointImplementationOutput} allowed for error responses.
|
|
9
|
+
*
|
|
10
|
+
* @category Internal
|
|
11
|
+
* @category Package : @rest-vir/implement-service
|
|
12
|
+
* @package [`@rest-vir/implement-service`](https://www.npmjs.com/package/@rest-vir/implement-service)
|
|
13
|
+
*/
|
|
14
|
+
export type EndpointImplementationErrorOutput = {
|
|
15
|
+
statusCode: HttpStatusByCategory<ErrorHttpStatusCategories>;
|
|
16
|
+
/**
|
|
17
|
+
* An error message which will get sent to the frontend.
|
|
18
|
+
*
|
|
19
|
+
* DO NOT INCLUDE SENSITIVE INFORMATION IN HERE.
|
|
20
|
+
*/
|
|
21
|
+
responseErrorMessage?: string | undefined;
|
|
22
|
+
responseData?: undefined;
|
|
23
|
+
headers?: OutgoingHttpHeaders | undefined;
|
|
24
|
+
dataType?: undefined;
|
|
25
|
+
};
|
|
26
|
+
/**
|
|
27
|
+
* The object that all endpoint implementations should return.
|
|
28
|
+
*
|
|
29
|
+
* @category Internal
|
|
30
|
+
* @category Package : @rest-vir/implement-service
|
|
31
|
+
* @package [`@rest-vir/implement-service`](https://www.npmjs.com/package/@rest-vir/implement-service)
|
|
32
|
+
*/
|
|
33
|
+
export type EndpointImplementationOutput<ResponseDataType = unknown> = EndpointImplementationErrorOutput | ({
|
|
34
|
+
statusCode: HttpStatusByCategory<SuccessHttpStatusCategories>;
|
|
35
|
+
responseErrorMessage?: never;
|
|
36
|
+
/**
|
|
37
|
+
* Set the response data type. If any response data is included, the default is
|
|
38
|
+
* `application/json`.
|
|
39
|
+
*/
|
|
40
|
+
dataType?: string | undefined;
|
|
41
|
+
headers?: OutgoingHttpHeaders | undefined;
|
|
42
|
+
} & (ResponseDataType extends undefined ? {
|
|
43
|
+
responseData?: ResponseDataType;
|
|
44
|
+
} : {
|
|
45
|
+
responseData: ResponseDataType;
|
|
46
|
+
}));
|
|
47
|
+
/**
|
|
48
|
+
* The object that all endpoint implementations receive as an input.
|
|
49
|
+
*
|
|
50
|
+
* @category Internal
|
|
51
|
+
* @category Package : @rest-vir/implement-service
|
|
52
|
+
* @package [`@rest-vir/implement-service`](https://www.npmjs.com/package/@rest-vir/implement-service)
|
|
53
|
+
*/
|
|
54
|
+
export type EndpointImplementationParams<Context = any, ServiceName extends string = any, SpecificEndpoint extends EndpointDefinition | NoParam = NoParam> = {
|
|
55
|
+
pathParams: SpecificEndpoint extends NoParam ? Readonly<Record<string, string>> : PathParams<Exclude<SpecificEndpoint, NoParam>['path']> extends string ? Readonly<Record<PathParams<Exclude<SpecificEndpoint, NoParam>['path']>, string>> : Readonly<Record<string, string>>;
|
|
56
|
+
context: Context;
|
|
57
|
+
method: IsEqual<Extract<SpecificEndpoint, NoParam>, NoParam> extends true ? HttpMethod : ExtractKeysWithMatchingValues<Exclude<SpecificEndpoint, NoParam>['methods'], true> extends infer AvailableMethod ? IsNever<AvailableMethod> extends true ? HttpMethod : AvailableMethod : never;
|
|
58
|
+
endpoint: IsEqual<Extract<SpecificEndpoint, NoParam>, NoParam> extends true ? EndpointDefinition : SpecificEndpoint;
|
|
59
|
+
service: MinimalService<ServiceName>;
|
|
60
|
+
requestHeaders: IncomingHttpHeaders;
|
|
61
|
+
requestData: IsEqual<Extract<SpecificEndpoint, NoParam>, NoParam> extends true ? any : WithFinalEndpointProps<Exclude<SpecificEndpoint, NoParam>, any>['RequestType'];
|
|
62
|
+
request: ServerRequest;
|
|
63
|
+
response: ServerResponse;
|
|
64
|
+
log: Readonly<ServiceLogger>;
|
|
65
|
+
searchParams: SpecificEndpoint extends NoParam ? BaseSearchParams : Exclude<SpecificEndpoint, NoParam>['SearchParamsType'];
|
|
66
|
+
};
|
|
67
|
+
/**
|
|
68
|
+
* Generic parameters for {@link EndpointImplementation} that should be compatible with _any_
|
|
69
|
+
* endpoint implementation.
|
|
70
|
+
*
|
|
71
|
+
* @category Internal
|
|
72
|
+
* @category Package : @rest-vir/implement-service
|
|
73
|
+
* @package [`@rest-vir/implement-service`](https://www.npmjs.com/package/@rest-vir/implement-service)
|
|
74
|
+
*/
|
|
75
|
+
export type GenericEndpointImplementationParams = {
|
|
76
|
+
context: any;
|
|
77
|
+
method: any;
|
|
78
|
+
endpoint: any;
|
|
79
|
+
service: MinimalService<any>;
|
|
80
|
+
requestHeaders: IncomingHttpHeaders;
|
|
81
|
+
searchParams: BaseSearchParams;
|
|
82
|
+
pathParams: Readonly<Record<string, string>>;
|
|
83
|
+
requestData: any;
|
|
84
|
+
request: ServerRequest;
|
|
85
|
+
response: ServerResponse;
|
|
86
|
+
log: Readonly<ServiceLogger>;
|
|
87
|
+
};
|
|
88
|
+
/**
|
|
89
|
+
* A full, type-safe endpoint implementation type.
|
|
90
|
+
*
|
|
91
|
+
* @category Internal
|
|
92
|
+
* @category Package : @rest-vir/implement-service
|
|
93
|
+
* @package [`@rest-vir/implement-service`](https://www.npmjs.com/package/@rest-vir/implement-service)
|
|
94
|
+
*/
|
|
95
|
+
export type EndpointImplementation<Context = any, ServiceName extends string = any, SpecificEndpoint extends EndpointDefinition | NoParam = NoParam> = IsEqual<Extract<SpecificEndpoint, NoParam>, NoParam> extends true ? (params: GenericEndpointImplementationParams) => any : (params: Readonly<EndpointImplementationParams<Context, ServiceName, SpecificEndpoint>>) => MaybePromise<EndpointImplementationOutput<WithFinalEndpointProps<SpecificEndpoint, any>['ResponseType']>>;
|
|
96
|
+
/**
|
|
97
|
+
* All endpoint implementations to match the service definition's endpoints.
|
|
98
|
+
*
|
|
99
|
+
* @category Internal
|
|
100
|
+
* @category Package : @rest-vir/implement-service
|
|
101
|
+
* @package [`@rest-vir/implement-service`](https://www.npmjs.com/package/@rest-vir/implement-service)
|
|
102
|
+
*/
|
|
103
|
+
export type EndpointImplementations<Context = any, ServiceName extends string = any, EndpointsInit extends BaseServiceEndpointsInit | NoParam = NoParam> = EndpointsInit extends NoParam ? Record<EndpointPathBase, EndpointImplementation> : {
|
|
104
|
+
[EndpointPath in keyof EndpointsInit]: EndpointsInit[EndpointPath] extends EndpointInit ? EndpointPath extends EndpointPathBase ? EndpointImplementation<Context, ServiceName, WithFinalEndpointProps<EndpointsInit[EndpointPath], EndpointPath>> : never : never;
|
|
105
|
+
};
|
|
106
|
+
/**
|
|
107
|
+
* Asserts that all endpoint implementations are valid.
|
|
108
|
+
*
|
|
109
|
+
* @category Internal
|
|
110
|
+
* @category Package : @rest-vir/implement-service
|
|
111
|
+
* @package [`@rest-vir/implement-service`](https://www.npmjs.com/package/@rest-vir/implement-service)
|
|
112
|
+
*/
|
|
113
|
+
export declare function assertValidEndpointImplementations(service: Readonly<Pick<ServiceDefinition, 'endpoints' | 'serviceName'>>, endpointImplementations: EndpointImplementations): asserts endpointImplementations is Record<EndpointPathBase, EndpointImplementation>;
|
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
import { check } from '@augment-vir/assert';
|
|
2
|
+
import { getObjectTypedEntries, } from '@augment-vir/common';
|
|
3
|
+
import { ServiceDefinitionError, } from '@rest-vir/define-service';
|
|
4
|
+
/**
|
|
5
|
+
* Asserts that all endpoint implementations are valid.
|
|
6
|
+
*
|
|
7
|
+
* @category Internal
|
|
8
|
+
* @category Package : @rest-vir/implement-service
|
|
9
|
+
* @package [`@rest-vir/implement-service`](https://www.npmjs.com/package/@rest-vir/implement-service)
|
|
10
|
+
*/
|
|
11
|
+
export function assertValidEndpointImplementations(service, endpointImplementations) {
|
|
12
|
+
const nonFunctionImplementations = getObjectTypedEntries(endpointImplementations).filter(([, implementation,]) => {
|
|
13
|
+
return check.isNotFunction(implementation);
|
|
14
|
+
});
|
|
15
|
+
if (nonFunctionImplementations.length) {
|
|
16
|
+
throw new ServiceDefinitionError({
|
|
17
|
+
path: undefined,
|
|
18
|
+
errorMessage: `Endpoint implementations are not functions for endpoints: '${nonFunctionImplementations
|
|
19
|
+
.map(([endpointPath]) => endpointPath)
|
|
20
|
+
.join(',')}'`,
|
|
21
|
+
serviceName: service.serviceName,
|
|
22
|
+
isEndpoint: undefined,
|
|
23
|
+
isWebSocket: undefined,
|
|
24
|
+
});
|
|
25
|
+
}
|
|
26
|
+
const missingEndpointImplementationPaths = [];
|
|
27
|
+
const extraEndpointImplementationPaths = [];
|
|
28
|
+
Object.keys(service.endpoints).forEach((key) => {
|
|
29
|
+
if (!(key in endpointImplementations)) {
|
|
30
|
+
missingEndpointImplementationPaths.push(key);
|
|
31
|
+
}
|
|
32
|
+
});
|
|
33
|
+
Object.keys(endpointImplementations).forEach((key) => {
|
|
34
|
+
if (!(key in service.endpoints)) {
|
|
35
|
+
extraEndpointImplementationPaths.push(key);
|
|
36
|
+
}
|
|
37
|
+
});
|
|
38
|
+
if (missingEndpointImplementationPaths.length) {
|
|
39
|
+
throw new ServiceDefinitionError({
|
|
40
|
+
path: undefined,
|
|
41
|
+
errorMessage: `Endpoints are missing implementations: '${missingEndpointImplementationPaths.join(',')}'`,
|
|
42
|
+
serviceName: service.serviceName,
|
|
43
|
+
isEndpoint: undefined,
|
|
44
|
+
isWebSocket: undefined,
|
|
45
|
+
});
|
|
46
|
+
}
|
|
47
|
+
if (extraEndpointImplementationPaths.length) {
|
|
48
|
+
throw new ServiceDefinitionError({
|
|
49
|
+
path: undefined,
|
|
50
|
+
errorMessage: `Endpoint implementations have extra endpoints: '${extraEndpointImplementationPaths.join(',')}'`,
|
|
51
|
+
serviceName: service.serviceName,
|
|
52
|
+
isEndpoint: undefined,
|
|
53
|
+
isWebSocket: undefined,
|
|
54
|
+
});
|
|
55
|
+
}
|
|
56
|
+
}
|
|
@@ -0,0 +1,91 @@
|
|
|
1
|
+
import { type KeyCount, type MaybePromise } from '@augment-vir/common';
|
|
2
|
+
import { BaseServiceEndpointsInit, EndpointPathBase, NoParam, ServiceDefinition, type BaseServiceWebSocketsInit } from '@rest-vir/define-service';
|
|
3
|
+
import { type IsEqual, type OmitIndexSignature } from 'type-fest';
|
|
4
|
+
import { ServiceLoggerOption, type ServiceLogger } from '../util/service-logger.js';
|
|
5
|
+
import { type ImplementedEndpoint, type ImplementedWebSocket } from './generic-service-implementation.js';
|
|
6
|
+
import { type EndpointImplementations } from './implement-endpoint.js';
|
|
7
|
+
import { WebSocketImplementations } from './implement-web-socket.js';
|
|
8
|
+
import { type ContextInit } from './service-context-init.js';
|
|
9
|
+
/**
|
|
10
|
+
* A user-defined endpoint error handler for service (and its endpoints) errors.
|
|
11
|
+
*
|
|
12
|
+
* @category Internal
|
|
13
|
+
* @category Package : @rest-vir/implement-service
|
|
14
|
+
* @package [`@rest-vir/implement-service`](https://www.npmjs.com/package/@rest-vir/implement-service)
|
|
15
|
+
*/
|
|
16
|
+
export type CustomErrorHandler = (error: Error) => MaybePromise<void>;
|
|
17
|
+
/**
|
|
18
|
+
* Type-safe input for {@link implementService}.
|
|
19
|
+
*
|
|
20
|
+
* @category Internal
|
|
21
|
+
* @category Package : @rest-vir/implement-service
|
|
22
|
+
* @package [`@rest-vir/implement-service`](https://www.npmjs.com/package/@rest-vir/implement-service)
|
|
23
|
+
*/
|
|
24
|
+
export type ServiceImplementationInit<Context, ServiceName extends string, EndpointsInit extends BaseServiceEndpointsInit, WebSocketsInit extends BaseServiceWebSocketsInit> = {
|
|
25
|
+
service: ServiceDefinition<ServiceName, EndpointsInit, WebSocketsInit>;
|
|
26
|
+
/**
|
|
27
|
+
* Logger for the service. Use {@link silentServiceLogger} to disable logging entirely (even
|
|
28
|
+
* errors) or simply set `undefined` to the log type that you wish to suppress. An omitted log
|
|
29
|
+
* keys will fallback to the efault logger.
|
|
30
|
+
*/
|
|
31
|
+
logger?: ServiceLoggerOption;
|
|
32
|
+
} & (IsEqual<Context, undefined> extends true ? {
|
|
33
|
+
createContext?: undefined | ContextInit<Context, NoInfer<ServiceName>, NoInfer<EndpointsInit>, NoInfer<WebSocketsInit>>;
|
|
34
|
+
} : {
|
|
35
|
+
createContext: ContextInit<Context, NoInfer<ServiceName>, NoInfer<EndpointsInit>, NoInfer<WebSocketsInit>>;
|
|
36
|
+
});
|
|
37
|
+
/**
|
|
38
|
+
* Parameters for implementations for {@link implementService}.
|
|
39
|
+
*
|
|
40
|
+
* @category Internal
|
|
41
|
+
* @category Package : @rest-vir/implement-service
|
|
42
|
+
* @package [`@rest-vir/implement-service`](https://www.npmjs.com/package/@rest-vir/implement-service)
|
|
43
|
+
*/
|
|
44
|
+
export type ServiceImplementationsParams<Context, ServiceName extends string, EndpointsInit extends BaseServiceEndpointsInit, WebSocketsInit extends BaseServiceWebSocketsInit> = (KeyCount<OmitIndexSignature<EndpointsInit>> extends 0 ? {
|
|
45
|
+
endpoints?: never;
|
|
46
|
+
} : {
|
|
47
|
+
endpoints: EndpointImplementations<NoInfer<Context>, NoInfer<ServiceName>, NoInfer<EndpointsInit>>;
|
|
48
|
+
}) & (KeyCount<OmitIndexSignature<WebSocketsInit>> extends 0 ? {
|
|
49
|
+
webSockets?: never;
|
|
50
|
+
} : {
|
|
51
|
+
webSockets: WebSocketImplementations<NoInfer<Context>, NoInfer<ServiceName>, NoInfer<WebSocketsInit>>;
|
|
52
|
+
});
|
|
53
|
+
/**
|
|
54
|
+
* Creates an implemented service that is fully ready to be run as a server by attaching endpoint
|
|
55
|
+
* implementations to the given {@link ServiceDefinition}.
|
|
56
|
+
*
|
|
57
|
+
* This can _only_ be run in backend code.
|
|
58
|
+
*
|
|
59
|
+
* @category Implement Service
|
|
60
|
+
* @category Package : @rest-vir/implement-service
|
|
61
|
+
* @package [`@rest-vir/implement-service`](https://www.npmjs.com/package/@rest-vir/implement-service)
|
|
62
|
+
*/
|
|
63
|
+
export declare function implementService<const ServiceName extends string, const EndpointsInit extends BaseServiceEndpointsInit, const WebSocketsInit extends BaseServiceWebSocketsInit, const Context = undefined>(
|
|
64
|
+
/** Init must be first so that TypeScript can infer the type for `Context`. */
|
|
65
|
+
{ service, createContext, logger, }: ServiceImplementationInit<Context, ServiceName, EndpointsInit, WebSocketsInit>, { endpoints: endpointImplementations, webSockets: webSocketImplementations, }: ServiceImplementationsParams<NoInfer<Context>, NoInfer<ServiceName>, NoInfer<EndpointsInit>, NoInfer<WebSocketsInit>>): ServiceImplementation<Context, ServiceName, EndpointsInit, WebSocketsInit>;
|
|
66
|
+
/**
|
|
67
|
+
* A finalized service implementation created by {@link implementService}.
|
|
68
|
+
*
|
|
69
|
+
* @category Internal
|
|
70
|
+
* @category Package : @rest-vir/implement-service
|
|
71
|
+
* @package [`@rest-vir/implement-service`](https://www.npmjs.com/package/@rest-vir/implement-service)
|
|
72
|
+
*/
|
|
73
|
+
export type ServiceImplementation<Context = any, ServiceName extends string = any, EndpointsInit extends BaseServiceEndpointsInit | NoParam = NoParam, WebSocketsInit extends BaseServiceWebSocketsInit | NoParam = NoParam> = Omit<ServiceDefinition<ServiceName, EndpointsInit, WebSocketsInit>, 'endpoints' | 'webSockets'> & {
|
|
74
|
+
endpoints: {
|
|
75
|
+
[EndpointPath in keyof ServiceDefinition<ServiceName, EndpointsInit, WebSocketsInit>['endpoints']]: EndpointPath extends EndpointPathBase ? ImplementedEndpoint<Context, ServiceName, ServiceDefinition<ServiceName, EndpointsInit, WebSocketsInit>['endpoints'][EndpointPath]> : never;
|
|
76
|
+
};
|
|
77
|
+
webSockets: {
|
|
78
|
+
[WebSocketPath in keyof ServiceDefinition<ServiceName, EndpointsInit, WebSocketsInit>['webSockets']]: WebSocketPath extends EndpointPathBase ? ImplementedWebSocket<Context, ServiceName, ServiceDefinition<ServiceName, EndpointsInit, WebSocketsInit>['webSockets'][WebSocketPath]> : never;
|
|
79
|
+
};
|
|
80
|
+
createContext: ContextInit<Context, ServiceName, EndpointsInit, WebSocketsInit> | undefined;
|
|
81
|
+
logger: ServiceLogger;
|
|
82
|
+
};
|
|
83
|
+
/**
|
|
84
|
+
* A type util that converts a {@link ServiceDefinition} instance type into its companion
|
|
85
|
+
* {@link ServiceImplementation} type.
|
|
86
|
+
*
|
|
87
|
+
* @category Internal
|
|
88
|
+
* @category Package : @rest-vir/implement-service
|
|
89
|
+
* @package [`@rest-vir/implement-service`](https://www.npmjs.com/package/@rest-vir/implement-service)
|
|
90
|
+
*/
|
|
91
|
+
export type ServiceImplementationFromServiceDefinition<SpecificServiceDefinition extends ServiceDefinition> = SpecificServiceDefinition extends ServiceDefinition<infer ServiceName, infer EndpointInit, infer WebSocketInit> ? ServiceImplementation<unknown, ServiceName, EndpointInit, WebSocketInit> : 'ERROR: Failed to infer service definition type parameters';
|
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
import { assert } from '@augment-vir/assert';
|
|
2
|
+
import { mapObjectValues, } from '@augment-vir/common';
|
|
3
|
+
import { createServiceLogger, } from '../util/service-logger.js';
|
|
4
|
+
import { assertValidEndpointImplementations, } from './implement-endpoint.js';
|
|
5
|
+
import { assertValidWebSocketImplementations, } from './implement-web-socket.js';
|
|
6
|
+
/**
|
|
7
|
+
* Creates an implemented service that is fully ready to be run as a server by attaching endpoint
|
|
8
|
+
* implementations to the given {@link ServiceDefinition}.
|
|
9
|
+
*
|
|
10
|
+
* This can _only_ be run in backend code.
|
|
11
|
+
*
|
|
12
|
+
* @category Implement Service
|
|
13
|
+
* @category Package : @rest-vir/implement-service
|
|
14
|
+
* @package [`@rest-vir/implement-service`](https://www.npmjs.com/package/@rest-vir/implement-service)
|
|
15
|
+
*/
|
|
16
|
+
export function implementService(
|
|
17
|
+
/** Init must be first so that TypeScript can infer the type for `Context`. */
|
|
18
|
+
{ service, createContext, logger, }, { endpoints: endpointImplementations, webSockets: webSocketImplementations, }) {
|
|
19
|
+
assertValidEndpointImplementations(service, endpointImplementations || {});
|
|
20
|
+
assertValidWebSocketImplementations(service, webSocketImplementations || {});
|
|
21
|
+
const endpoints = mapObjectValues(service.endpoints, (endpointPath, endpoint) => {
|
|
22
|
+
const implementation = endpointImplementations?.[endpointPath];
|
|
23
|
+
assert.isDefined(implementation);
|
|
24
|
+
assert.isNotString(implementation);
|
|
25
|
+
/**
|
|
26
|
+
* Note: this return object is actually wrong. The service property will not be correct as
|
|
27
|
+
* the `endpoint` here only has the minimal service. Below, after `serviceImplementation` is
|
|
28
|
+
* created, we attach the correct service to all endpoints.
|
|
29
|
+
*/
|
|
30
|
+
return {
|
|
31
|
+
...endpoint,
|
|
32
|
+
implementation,
|
|
33
|
+
};
|
|
34
|
+
});
|
|
35
|
+
const webSockets = mapObjectValues(service.webSockets, (webSocketPath, webSocketImplementation) => {
|
|
36
|
+
const implementation = webSocketImplementations?.[webSocketPath];
|
|
37
|
+
assert.isDefined(implementation);
|
|
38
|
+
assert.isNotString(webSocketImplementation);
|
|
39
|
+
/**
|
|
40
|
+
* Note: this return object is actually wrong. The service property will not be correct
|
|
41
|
+
* as the WebSocket here only has the minimal service. Below, after
|
|
42
|
+
* `serviceImplementation` is created, we attach the correct service to all WebSockets.
|
|
43
|
+
*/
|
|
44
|
+
return {
|
|
45
|
+
...webSocketImplementation,
|
|
46
|
+
implementation,
|
|
47
|
+
};
|
|
48
|
+
});
|
|
49
|
+
const serviceImplementation = {
|
|
50
|
+
...service,
|
|
51
|
+
endpoints,
|
|
52
|
+
webSockets,
|
|
53
|
+
createContext,
|
|
54
|
+
logger: createServiceLogger(logger),
|
|
55
|
+
};
|
|
56
|
+
Object.values(endpoints).forEach((endpoint) => {
|
|
57
|
+
endpoint.service = serviceImplementation;
|
|
58
|
+
});
|
|
59
|
+
Object.values(webSockets).forEach((webSocket) => {
|
|
60
|
+
webSocket.service = serviceImplementation;
|
|
61
|
+
});
|
|
62
|
+
return serviceImplementation;
|
|
63
|
+
}
|
|
@@ -0,0 +1,67 @@
|
|
|
1
|
+
import { type MaybePromise } from '@augment-vir/common';
|
|
2
|
+
import { BaseSearchParams, BaseServiceWebSocketsInit, EndpointPathBase, MinimalService, NoParam, ServiceDefinition, WebSocketDefinition, WebSocketInit, WithFinalWebSocketProps } from '@rest-vir/define-service';
|
|
3
|
+
import { type IncomingHttpHeaders } from 'node:http';
|
|
4
|
+
import { type IsEqual } from 'type-fest';
|
|
5
|
+
import { type ServerRequest, type ServerWebSocket } from '../util/data.js';
|
|
6
|
+
import { type ServiceLogger } from '../util/service-logger.js';
|
|
7
|
+
/**
|
|
8
|
+
* A WebSocket implementation, with callbacks for WebSocket events.
|
|
9
|
+
*
|
|
10
|
+
* @category Internal
|
|
11
|
+
* @category Package : @rest-vir/implement-service
|
|
12
|
+
* @package [`@rest-vir/implement-service`](https://www.npmjs.com/package/@rest-vir/implement-service)
|
|
13
|
+
*/
|
|
14
|
+
export type WebSocketImplementation<Context = any, ServiceName extends string = any, SpecificWebSocket extends WebSocketDefinition | NoParam = NoParam> = SpecificWebSocket extends NoParam ? any : Partial<{
|
|
15
|
+
/** This will be called when the WebSocket is connected and created. */
|
|
16
|
+
onConnection: (params: WebSocketImplementationParams<Context, ServiceName, SpecificWebSocket, false>) => MaybePromise<void>;
|
|
17
|
+
/**
|
|
18
|
+
* This will be called on every received WebSocket message.
|
|
19
|
+
*
|
|
20
|
+
* @see https://github.com/websockets/ws/blob/HEAD/doc/ws.md#event-message
|
|
21
|
+
*/
|
|
22
|
+
onMessage: (params: WebSocketImplementationParams<Context, ServiceName, SpecificWebSocket, true>) => MaybePromise<void>;
|
|
23
|
+
/**
|
|
24
|
+
* This will be called when the WebSocket is closed.
|
|
25
|
+
*
|
|
26
|
+
* @see https://github.com/websockets/ws/blob/HEAD/doc/ws.md#event-close-1
|
|
27
|
+
*/
|
|
28
|
+
onClose: (params: WebSocketImplementationParams<Context, ServiceName, SpecificWebSocket, false>) => MaybePromise<void>;
|
|
29
|
+
}>;
|
|
30
|
+
/**
|
|
31
|
+
* Parameters for event callbacks in {@link WebSocketImplementation}.
|
|
32
|
+
*
|
|
33
|
+
* @category Internal
|
|
34
|
+
* @category Package : @rest-vir/implement-service
|
|
35
|
+
* @package [`@rest-vir/implement-service`](https://www.npmjs.com/package/@rest-vir/implement-service)
|
|
36
|
+
*/
|
|
37
|
+
export type WebSocketImplementationParams<Context = any, ServiceName extends string = any, SpecificWebSocket extends WebSocketDefinition | NoParam = NoParam, WithMessage extends boolean = boolean> = {
|
|
38
|
+
context: Context;
|
|
39
|
+
webSocket: ServerWebSocket<SpecificWebSocket>;
|
|
40
|
+
webSocketDefinition: IsEqual<Extract<SpecificWebSocket, NoParam>, NoParam> extends true ? WebSocketDefinition : SpecificWebSocket;
|
|
41
|
+
log: Readonly<ServiceLogger>;
|
|
42
|
+
service: MinimalService<ServiceName>;
|
|
43
|
+
headers: IncomingHttpHeaders;
|
|
44
|
+
request: ServerRequest;
|
|
45
|
+
protocols: SpecificWebSocket extends NoParam ? string[] : Exclude<SpecificWebSocket, NoParam>['ProtocolsType'];
|
|
46
|
+
searchParams: SpecificWebSocket extends NoParam ? BaseSearchParams : Exclude<SpecificWebSocket, NoParam>['SearchParamsType'];
|
|
47
|
+
} & (IsEqual<WithMessage, true> extends true ? {
|
|
48
|
+
message: SpecificWebSocket extends NoParam ? any : Exclude<SpecificWebSocket, NoParam>['MessageFromClientType'];
|
|
49
|
+
} : unknown);
|
|
50
|
+
/**
|
|
51
|
+
* All WebSockets implementations to match the service definition's WebSockets.
|
|
52
|
+
*
|
|
53
|
+
* @category Internal
|
|
54
|
+
* @category Package : @rest-vir/implement-service
|
|
55
|
+
* @package [`@rest-vir/implement-service`](https://www.npmjs.com/package/@rest-vir/implement-service)
|
|
56
|
+
*/
|
|
57
|
+
export type WebSocketImplementations<Context = any, ServiceName extends string = any, WebSocketsInit extends BaseServiceWebSocketsInit | NoParam = NoParam> = WebSocketsInit extends NoParam ? Record<EndpointPathBase, WebSocketImplementation> : {
|
|
58
|
+
[WebSocketPath in keyof WebSocketsInit]: WebSocketsInit[WebSocketPath] extends WebSocketInit ? WebSocketPath extends EndpointPathBase ? WebSocketImplementation<Context, ServiceName, WithFinalWebSocketProps<WebSocketsInit[WebSocketPath], WebSocketPath>> : never : never;
|
|
59
|
+
};
|
|
60
|
+
/**
|
|
61
|
+
* Asserts that all WebSocket implementations are valid.
|
|
62
|
+
*
|
|
63
|
+
* @category Internal
|
|
64
|
+
* @category Package : @rest-vir/implement-service
|
|
65
|
+
* @package [`@rest-vir/implement-service`](https://www.npmjs.com/package/@rest-vir/implement-service)
|
|
66
|
+
*/
|
|
67
|
+
export declare function assertValidWebSocketImplementations(service: Pick<ServiceDefinition, 'webSockets' | 'serviceName'>, webSocketImplementations: WebSocketImplementations): void;
|
|
@@ -0,0 +1,72 @@
|
|
|
1
|
+
import { check } from '@augment-vir/assert';
|
|
2
|
+
import { filterMap, getObjectTypedEntries, getObjectTypedKeys, } from '@augment-vir/common';
|
|
3
|
+
import { ServiceDefinitionError, } from '@rest-vir/define-service';
|
|
4
|
+
/**
|
|
5
|
+
* Asserts that all WebSocket implementations are valid.
|
|
6
|
+
*
|
|
7
|
+
* @category Internal
|
|
8
|
+
* @category Package : @rest-vir/implement-service
|
|
9
|
+
* @package [`@rest-vir/implement-service`](https://www.npmjs.com/package/@rest-vir/implement-service)
|
|
10
|
+
*/
|
|
11
|
+
export function assertValidWebSocketImplementations(service, webSocketImplementations) {
|
|
12
|
+
const nonFunctionImplementations = filterMap(getObjectTypedEntries(webSocketImplementations), ([webSocketPath, webSocketImplementation,]) => {
|
|
13
|
+
const nonFunctionKeys = getObjectTypedKeys(webSocketImplementation).filter((key) => {
|
|
14
|
+
const callback = webSocketImplementation[key];
|
|
15
|
+
return callback && check.isNotFunction(callback);
|
|
16
|
+
});
|
|
17
|
+
if (nonFunctionKeys.length) {
|
|
18
|
+
return {
|
|
19
|
+
path: webSocketPath,
|
|
20
|
+
nonFunctionKeys,
|
|
21
|
+
};
|
|
22
|
+
}
|
|
23
|
+
else {
|
|
24
|
+
return undefined;
|
|
25
|
+
}
|
|
26
|
+
}, check.isTruthy);
|
|
27
|
+
if (nonFunctionImplementations.length) {
|
|
28
|
+
const invalidFunctionsString = nonFunctionImplementations
|
|
29
|
+
.map(({ nonFunctionKeys, path }) => [
|
|
30
|
+
path,
|
|
31
|
+
nonFunctionKeys.join(','),
|
|
32
|
+
].join(': '))
|
|
33
|
+
.join(';\n');
|
|
34
|
+
throw new ServiceDefinitionError({
|
|
35
|
+
path: undefined,
|
|
36
|
+
errorMessage: `WebSockets implementations are not functions for:\n${invalidFunctionsString}`,
|
|
37
|
+
serviceName: service.serviceName,
|
|
38
|
+
isEndpoint: undefined,
|
|
39
|
+
isWebSocket: undefined,
|
|
40
|
+
});
|
|
41
|
+
}
|
|
42
|
+
const missingImplementationPaths = [];
|
|
43
|
+
const extraImplementationPaths = [];
|
|
44
|
+
Object.keys(service.webSockets).forEach((key) => {
|
|
45
|
+
if (!(key in webSocketImplementations)) {
|
|
46
|
+
missingImplementationPaths.push(key);
|
|
47
|
+
}
|
|
48
|
+
});
|
|
49
|
+
Object.keys(webSocketImplementations).forEach((key) => {
|
|
50
|
+
if (!(key in service.webSockets)) {
|
|
51
|
+
extraImplementationPaths.push(key);
|
|
52
|
+
}
|
|
53
|
+
});
|
|
54
|
+
if (missingImplementationPaths.length) {
|
|
55
|
+
throw new ServiceDefinitionError({
|
|
56
|
+
path: undefined,
|
|
57
|
+
errorMessage: `WebSockets are missing implementations: '${missingImplementationPaths.join(',')}'`,
|
|
58
|
+
serviceName: service.serviceName,
|
|
59
|
+
isEndpoint: undefined,
|
|
60
|
+
isWebSocket: undefined,
|
|
61
|
+
});
|
|
62
|
+
}
|
|
63
|
+
if (extraImplementationPaths.length) {
|
|
64
|
+
throw new ServiceDefinitionError({
|
|
65
|
+
path: undefined,
|
|
66
|
+
errorMessage: `WebSocket implementations have extra paths: '${extraImplementationPaths.join(',')}'`,
|
|
67
|
+
serviceName: service.serviceName,
|
|
68
|
+
isEndpoint: undefined,
|
|
69
|
+
isWebSocket: undefined,
|
|
70
|
+
});
|
|
71
|
+
}
|
|
72
|
+
}
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
import { HttpMethod, MaybePromise, Values } from '@augment-vir/common';
|
|
2
|
+
import { type BaseServiceEndpointsInit, type BaseServiceWebSocketsInit, type EndpointDefinition, type EndpointPathBase, type MinimalService, type NoParam, type WebSocketDefinition, type WithFinalEndpointProps, type WithFinalWebSocketProps } from '@rest-vir/define-service';
|
|
3
|
+
import { type IncomingHttpHeaders } from 'node:http';
|
|
4
|
+
import { type RequireExactlyOne } from 'type-fest';
|
|
5
|
+
import { type ServerRequest, type ServerResponse } from '../util/data.js';
|
|
6
|
+
import { EndpointImplementationErrorOutput } from './implement-endpoint.js';
|
|
7
|
+
/**
|
|
8
|
+
* User-defined service implementation Context generator.
|
|
9
|
+
*
|
|
10
|
+
* @category Internal
|
|
11
|
+
* @category Package : @rest-vir/implement-service
|
|
12
|
+
* @package [`@rest-vir/implement-service`](https://www.npmjs.com/package/@rest-vir/implement-service)
|
|
13
|
+
*/
|
|
14
|
+
export type ContextInit<Context, ServiceName extends string, EndpointsInit extends BaseServiceEndpointsInit | NoParam, WebSocketsInit extends BaseServiceWebSocketsInit | NoParam> = (params: Readonly<ContextInitParameters<ServiceName, EndpointsInit, WebSocketsInit>>) => MaybePromise<RequireExactlyOne<{
|
|
15
|
+
/** The context created for this request. */
|
|
16
|
+
context: Context;
|
|
17
|
+
/**
|
|
18
|
+
* Instead of creating a context object for the current request, instead, reject the request
|
|
19
|
+
* with the specified status code and other options.
|
|
20
|
+
*/
|
|
21
|
+
reject: EndpointImplementationErrorOutput;
|
|
22
|
+
}>>;
|
|
23
|
+
/**
|
|
24
|
+
* Parameters for {@link ContextInit}.
|
|
25
|
+
*
|
|
26
|
+
* @category Internal
|
|
27
|
+
* @category Package : @rest-vir/implement-service
|
|
28
|
+
* @package [`@rest-vir/implement-service`](https://www.npmjs.com/package/@rest-vir/implement-service)
|
|
29
|
+
*/
|
|
30
|
+
export type ContextInitParameters<ServiceName extends string = any, EndpointsInit extends BaseServiceEndpointsInit | NoParam = NoParam, WebSocketsInit extends BaseServiceWebSocketsInit | NoParam = NoParam> = {
|
|
31
|
+
service: MinimalService<ServiceName>;
|
|
32
|
+
requestHeaders: IncomingHttpHeaders;
|
|
33
|
+
method: HttpMethod;
|
|
34
|
+
requestData: EndpointsInit extends NoParam ? unknown : WithFinalEndpointProps<Values<EndpointsInit>, Extract<keyof EndpointsInit, EndpointPathBase>>['RequestType'];
|
|
35
|
+
request: ServerRequest;
|
|
36
|
+
response: ServerResponse;
|
|
37
|
+
endpointDefinition?: (EndpointsInit extends NoParam ? EndpointDefinition : WithFinalEndpointProps<Values<EndpointsInit>, Extract<keyof EndpointsInit, EndpointPathBase>>) | undefined;
|
|
38
|
+
webSocketDefinition?: (WebSocketsInit extends NoParam ? WebSocketDefinition : WithFinalWebSocketProps<Values<WebSocketsInit>, Extract<keyof WebSocketsInit, EndpointPathBase>>) | undefined;
|
|
39
|
+
};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export {};
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
export { HttpMethod, HttpStatus } from '@augment-vir/common';
|
|
2
|
+
export * from './implementation/generic-service-implementation.js';
|
|
3
|
+
export * from './implementation/implement-endpoint.js';
|
|
4
|
+
export * from './implementation/implement-service.js';
|
|
5
|
+
export * from './implementation/implement-web-socket.js';
|
|
6
|
+
export * from './implementation/service-context-init.js';
|
|
7
|
+
export * from './util/data.js';
|
|
8
|
+
export * from './util/handler.error.js';
|
|
9
|
+
export * from './util/service-logger.js';
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
export { HttpMethod, HttpStatus } from '@augment-vir/common';
|
|
2
|
+
export * from './implementation/generic-service-implementation.js';
|
|
3
|
+
export * from './implementation/implement-endpoint.js';
|
|
4
|
+
export * from './implementation/implement-service.js';
|
|
5
|
+
export * from './implementation/implement-web-socket.js';
|
|
6
|
+
export * from './implementation/service-context-init.js';
|
|
7
|
+
export * from './util/data.js';
|
|
8
|
+
export * from './util/handler.error.js';
|
|
9
|
+
export * from './util/service-logger.js';
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
import { type NoParam, type OverwriteWebSocketMethods, type WebSocketDefinition, type WebSocketLocation } from '@rest-vir/define-service';
|
|
2
|
+
import { type FastifyReply, type FastifyRequest } from 'fastify';
|
|
3
|
+
import { type WebSocket as WsWebSocket } from 'ws';
|
|
4
|
+
/**
|
|
5
|
+
* A type alias for the request objects used by rest-vir. Currently this is the `FastifyRequest`
|
|
6
|
+
* object from Fastify.
|
|
7
|
+
*
|
|
8
|
+
* @category Internal
|
|
9
|
+
* @category Package : @rest-vir/implement-service
|
|
10
|
+
* @package [`@rest-vir/implement-service`](https://www.npmjs.com/package/@rest-vir/implement-service)
|
|
11
|
+
*/
|
|
12
|
+
export type ServerRequest = FastifyRequest;
|
|
13
|
+
/**
|
|
14
|
+
* A type alias for the response objects used by rest-vir. Currently this is the `FastifyReply`
|
|
15
|
+
* object from Fastify.
|
|
16
|
+
*
|
|
17
|
+
* @category Internal
|
|
18
|
+
* @category Package : @rest-vir/implement-service
|
|
19
|
+
* @package [`@rest-vir/implement-service`](https://www.npmjs.com/package/@rest-vir/implement-service)
|
|
20
|
+
*/
|
|
21
|
+
export type ServerResponse = FastifyReply;
|
|
22
|
+
/**
|
|
23
|
+
* A type alias for the WebSocket objects used by rest-vir. Currently this is the `WebSocket` object
|
|
24
|
+
* from the ws package.
|
|
25
|
+
*
|
|
26
|
+
* @category Internal
|
|
27
|
+
* @category Package : @rest-vir/implement-service
|
|
28
|
+
* @package [`@rest-vir/implement-service`](https://www.npmjs.com/package/@rest-vir/implement-service)
|
|
29
|
+
*/
|
|
30
|
+
export type ServerWebSocket<SpecificWebSocket extends WebSocketDefinition | NoParam> = OverwriteWebSocketMethods<WsWebSocket, WebSocketLocation.OnHost, SpecificWebSocket>;
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export {};
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* An error thrown internally from rest-vir while handling an request. This will not include errors
|
|
3
|
+
* thrown by an endpoint or WebSocket implementation itself.
|
|
4
|
+
*
|
|
5
|
+
* The default service logger will only log the message of these errors, not the whole stack track
|
|
6
|
+
* (so logs are easier to read).
|
|
7
|
+
*
|
|
8
|
+
* @category Internal
|
|
9
|
+
* @category Package : @rest-vir/implement-service
|
|
10
|
+
* @package [`@rest-vir/implement-service`](https://www.npmjs.com/package/@rest-vir/implement-service)
|
|
11
|
+
*/
|
|
12
|
+
export declare class RestVirHandlerError extends Error {
|
|
13
|
+
readonly name = "RestVirHandlerError";
|
|
14
|
+
constructor(route: Parameters<typeof createRestVirHandlerErrorPrefix>[0], message: string);
|
|
15
|
+
}
|
|
16
|
+
/**
|
|
17
|
+
* Creates the handler error string used by {@link RestVirHandlerError}.
|
|
18
|
+
*
|
|
19
|
+
* @category Internal
|
|
20
|
+
* @category Package : @rest-vir/implement-service
|
|
21
|
+
* @package [`@rest-vir/implement-service`](https://www.npmjs.com/package/@rest-vir/implement-service)
|
|
22
|
+
*/
|
|
23
|
+
export declare function createRestVirHandlerErrorPrefix(route: Readonly<{
|
|
24
|
+
path: string;
|
|
25
|
+
service: {
|
|
26
|
+
serviceName: string;
|
|
27
|
+
};
|
|
28
|
+
isWebSocket: boolean | undefined;
|
|
29
|
+
isEndpoint: boolean | undefined;
|
|
30
|
+
}>): string;
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
import { combineErrorMessages } from '@augment-vir/common';
|
|
2
|
+
/**
|
|
3
|
+
* An error thrown internally from rest-vir while handling an request. This will not include errors
|
|
4
|
+
* thrown by an endpoint or WebSocket implementation itself.
|
|
5
|
+
*
|
|
6
|
+
* The default service logger will only log the message of these errors, not the whole stack track
|
|
7
|
+
* (so logs are easier to read).
|
|
8
|
+
*
|
|
9
|
+
* @category Internal
|
|
10
|
+
* @category Package : @rest-vir/implement-service
|
|
11
|
+
* @package [`@rest-vir/implement-service`](https://www.npmjs.com/package/@rest-vir/implement-service)
|
|
12
|
+
*/
|
|
13
|
+
export class RestVirHandlerError extends Error {
|
|
14
|
+
name = 'RestVirHandlerError';
|
|
15
|
+
constructor(route, message) {
|
|
16
|
+
super(combineErrorMessages(createRestVirHandlerErrorPrefix(route), message));
|
|
17
|
+
}
|
|
18
|
+
}
|
|
19
|
+
/**
|
|
20
|
+
* Creates the handler error string used by {@link RestVirHandlerError}.
|
|
21
|
+
*
|
|
22
|
+
* @category Internal
|
|
23
|
+
* @category Package : @rest-vir/implement-service
|
|
24
|
+
* @package [`@rest-vir/implement-service`](https://www.npmjs.com/package/@rest-vir/implement-service)
|
|
25
|
+
*/
|
|
26
|
+
export function createRestVirHandlerErrorPrefix(route) {
|
|
27
|
+
const routeNoun = route.isWebSocket ? 'WebSocket ' : route.isEndpoint ? 'Endpoint ' : '';
|
|
28
|
+
return `${routeNoun}'${route.path}' failed in service '${route.service.serviceName}'`;
|
|
29
|
+
}
|
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
import { type PartialWithUndefined } from '@augment-vir/common';
|
|
2
|
+
/**
|
|
3
|
+
* A service logger. All internal service logs will go through this and endpoint implementations are
|
|
4
|
+
* also given the service's logger to use if they wish.
|
|
5
|
+
*
|
|
6
|
+
* @category Internal
|
|
7
|
+
* @category Package : @rest-vir/implement-service
|
|
8
|
+
* @package [`@rest-vir/implement-service`](https://www.npmjs.com/package/@rest-vir/implement-service)
|
|
9
|
+
*/
|
|
10
|
+
export type ServiceLogger = {
|
|
11
|
+
/** The error log is always guaranteed to be passed exactly a single error. */
|
|
12
|
+
error: (error: Error) => void;
|
|
13
|
+
/**
|
|
14
|
+
* The info log maybe receive any number of arguments of any type. Note that
|
|
15
|
+
* {@link defaultServiceLogger} already contains logic to convert these into strings so you may
|
|
16
|
+
* want to utilize its behavior in your custom logging.
|
|
17
|
+
*/
|
|
18
|
+
info: (...args: ReadonlyArray<unknown>) => void;
|
|
19
|
+
};
|
|
20
|
+
/**
|
|
21
|
+
* User-definable service logger. Loggers may be set as `undefined` here to silence them.
|
|
22
|
+
*
|
|
23
|
+
* @category Internal
|
|
24
|
+
* @category Package : @rest-vir/implement-service
|
|
25
|
+
* @package [`@rest-vir/implement-service`](https://www.npmjs.com/package/@rest-vir/implement-service)
|
|
26
|
+
*/
|
|
27
|
+
export type ServiceLoggerOption = PartialWithUndefined<ServiceLogger>;
|
|
28
|
+
/**
|
|
29
|
+
* The efault service logger.
|
|
30
|
+
*
|
|
31
|
+
* @category Internal
|
|
32
|
+
* @category Package : @rest-vir/implement-service
|
|
33
|
+
* @package [`@rest-vir/implement-service`](https://www.npmjs.com/package/@rest-vir/implement-service)
|
|
34
|
+
*/
|
|
35
|
+
export declare const defaultServiceLogger: ServiceLogger;
|
|
36
|
+
/**
|
|
37
|
+
* Combines a user defined service logger with the default logger, silencing loggers that have been
|
|
38
|
+
* set to `undefined` by the user.
|
|
39
|
+
*
|
|
40
|
+
* @category Internal
|
|
41
|
+
* @category Package : @rest-vir/implement-service
|
|
42
|
+
* @package [`@rest-vir/implement-service`](https://www.npmjs.com/package/@rest-vir/implement-service)
|
|
43
|
+
*/
|
|
44
|
+
export declare function createServiceLogger(option?: ServiceLoggerOption): ServiceLogger;
|
|
45
|
+
/**
|
|
46
|
+
* A silent service logger. All logs simply do not get logged or do anything at all.
|
|
47
|
+
*
|
|
48
|
+
* @category Internal
|
|
49
|
+
* @category Package : @rest-vir/implement-service
|
|
50
|
+
* @package [`@rest-vir/implement-service`](https://www.npmjs.com/package/@rest-vir/implement-service)
|
|
51
|
+
*/
|
|
52
|
+
export declare const silentServiceLogger: ServiceLogger;
|
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
import { log, mapObjectValues } from '@augment-vir/common';
|
|
2
|
+
/**
|
|
3
|
+
* The efault service logger.
|
|
4
|
+
*
|
|
5
|
+
* @category Internal
|
|
6
|
+
* @category Package : @rest-vir/implement-service
|
|
7
|
+
* @package [`@rest-vir/implement-service`](https://www.npmjs.com/package/@rest-vir/implement-service)
|
|
8
|
+
*/
|
|
9
|
+
export const defaultServiceLogger = {
|
|
10
|
+
error(error) {
|
|
11
|
+
log.error(error);
|
|
12
|
+
},
|
|
13
|
+
info: log.faint,
|
|
14
|
+
};
|
|
15
|
+
/**
|
|
16
|
+
* Combines a user defined service logger with the default logger, silencing loggers that have been
|
|
17
|
+
* set to `undefined` by the user.
|
|
18
|
+
*
|
|
19
|
+
* @category Internal
|
|
20
|
+
* @category Package : @rest-vir/implement-service
|
|
21
|
+
* @package [`@rest-vir/implement-service`](https://www.npmjs.com/package/@rest-vir/implement-service)
|
|
22
|
+
*/
|
|
23
|
+
export function createServiceLogger(option = {}) {
|
|
24
|
+
return mapObjectValues(defaultServiceLogger, (logKey, defaultLogFunction) => {
|
|
25
|
+
if (logKey in option) {
|
|
26
|
+
return option[logKey] || silentServiceLogger[logKey];
|
|
27
|
+
}
|
|
28
|
+
else {
|
|
29
|
+
return defaultLogFunction;
|
|
30
|
+
}
|
|
31
|
+
});
|
|
32
|
+
}
|
|
33
|
+
/**
|
|
34
|
+
* A silent service logger. All logs simply do not get logged or do anything at all.
|
|
35
|
+
*
|
|
36
|
+
* @category Internal
|
|
37
|
+
* @category Package : @rest-vir/implement-service
|
|
38
|
+
* @package [`@rest-vir/implement-service`](https://www.npmjs.com/package/@rest-vir/implement-service)
|
|
39
|
+
*/
|
|
40
|
+
export const silentServiceLogger = {
|
|
41
|
+
error: () => { },
|
|
42
|
+
info: () => { },
|
|
43
|
+
};
|
package/package.json
ADDED
|
@@ -0,0 +1,64 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "@rest-vir/implement-service",
|
|
3
|
+
"version": "0.0.2",
|
|
4
|
+
"description": "Implement a service defined by @rest-vir/define-service.",
|
|
5
|
+
"keywords": [
|
|
6
|
+
"rest",
|
|
7
|
+
"api",
|
|
8
|
+
"express",
|
|
9
|
+
"service",
|
|
10
|
+
"backend",
|
|
11
|
+
"server",
|
|
12
|
+
"websocket",
|
|
13
|
+
"vir"
|
|
14
|
+
],
|
|
15
|
+
"homepage": "https://github.com/electrovir/rest-vir",
|
|
16
|
+
"bugs": {
|
|
17
|
+
"url": "https://github.com/electrovir/rest-vir/issues"
|
|
18
|
+
},
|
|
19
|
+
"repository": {
|
|
20
|
+
"type": "git",
|
|
21
|
+
"url": "git+https://github.com/electrovir/rest-vir.git"
|
|
22
|
+
},
|
|
23
|
+
"license": "(MIT or CC0 1.0)",
|
|
24
|
+
"author": {
|
|
25
|
+
"name": "electrovir",
|
|
26
|
+
"url": "https://github.com/electrovir"
|
|
27
|
+
},
|
|
28
|
+
"type": "module",
|
|
29
|
+
"main": "dist/index.js",
|
|
30
|
+
"module": "dist/index.js",
|
|
31
|
+
"types": "dist/index.d.ts",
|
|
32
|
+
"scripts": {
|
|
33
|
+
"compile": "virmator compile",
|
|
34
|
+
"docs": "md-code README.md",
|
|
35
|
+
"start": "tsx src/index.ts",
|
|
36
|
+
"test": "virmator test node",
|
|
37
|
+
"test:coverage": "npm run test coverage",
|
|
38
|
+
"test:docs": "npm run docs check",
|
|
39
|
+
"test:update": "npm test update"
|
|
40
|
+
},
|
|
41
|
+
"dependencies": {
|
|
42
|
+
"@augment-vir/assert": "^31.9.1",
|
|
43
|
+
"@augment-vir/common": "^31.9.1",
|
|
44
|
+
"@rest-vir/define-service": "^0.0.2",
|
|
45
|
+
"@types/ws": "^8.5.14",
|
|
46
|
+
"fastify": "^5.2.1",
|
|
47
|
+
"object-shape-tester": "^5.1.1",
|
|
48
|
+
"path-to-regexp": "^8.2.0",
|
|
49
|
+
"type-fest": "^4.35.0"
|
|
50
|
+
},
|
|
51
|
+
"devDependencies": {
|
|
52
|
+
"@augment-vir/test": "^31.9.1",
|
|
53
|
+
"@types/node": "^22.13.4",
|
|
54
|
+
"c8": "^10.1.3",
|
|
55
|
+
"istanbul-smart-text-reporter": "^1.1.5",
|
|
56
|
+
"markdown-code-example-inserter": "^3.0.3"
|
|
57
|
+
},
|
|
58
|
+
"engines": {
|
|
59
|
+
"node": ">=22"
|
|
60
|
+
},
|
|
61
|
+
"publishConfig": {
|
|
62
|
+
"access": "public"
|
|
63
|
+
}
|
|
64
|
+
}
|