@hodfords/nestjs-grpc-helper 12.3.1 → 12.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (70) hide show
  1. package/README.md +218 -1
  2. package/commands/generate-sdk.command.js +8 -2
  3. package/commands/generate-sdk.command.js.map +1 -1
  4. package/constants/sdk-toolchain.const.d.ts +25 -0
  5. package/constants/sdk-toolchain.const.js +38 -0
  6. package/constants/sdk-toolchain.const.js.map +1 -0
  7. package/decorators/grpc-param.decorator.js +5 -4
  8. package/decorators/grpc-param.decorator.js.map +1 -1
  9. package/decorators/property.decorator.js +6 -3
  10. package/decorators/property.decorator.js.map +1 -1
  11. package/documents/microservice-document.controller.d.ts +1 -1
  12. package/dto/sort.dto.d.ts +1 -1
  13. package/dto/sort.dto.js +1 -1
  14. package/dto/sort.dto.js.map +1 -1
  15. package/helpers/generate.helper.d.ts +4 -3
  16. package/helpers/generate.helper.js +41 -3
  17. package/helpers/generate.helper.js.map +1 -1
  18. package/helpers/grpc-method.helper.js +1 -3
  19. package/helpers/grpc-method.helper.js.map +1 -1
  20. package/helpers/sdk-naming.helper.d.ts +7 -0
  21. package/helpers/sdk-naming.helper.js +197 -0
  22. package/helpers/sdk-naming.helper.js.map +1 -0
  23. package/helpers/sdk-output.helper.d.ts +6 -0
  24. package/helpers/sdk-output.helper.js +84 -0
  25. package/helpers/sdk-output.helper.js.map +1 -0
  26. package/helpers/shell.helper.d.ts +4 -0
  27. package/helpers/shell.helper.js +36 -0
  28. package/helpers/shell.helper.js.map +1 -1
  29. package/helpers/wire-response.helper.d.ts +8 -0
  30. package/helpers/wire-response.helper.js +23 -0
  31. package/helpers/wire-response.helper.js.map +1 -0
  32. package/index.d.ts +3 -0
  33. package/index.js +3 -0
  34. package/index.js.map +1 -1
  35. package/package.json +3 -1
  36. package/sdk-stub/helpers/grpc.helper.d.ts +1 -0
  37. package/sdk-stub/helpers/grpc.helper.js +11 -13
  38. package/sdk-stub/helpers/grpc.helper.js.map +1 -1
  39. package/sdk-stub/helpers/grpc.helper.spec.ts +46 -0
  40. package/sdk-stub/helpers/grpc.helper.ts +19 -12
  41. package/services/generate-proto.service.d.ts +1 -1
  42. package/services/generate-proto.service.js +11 -19
  43. package/services/generate-proto.service.js.map +1 -1
  44. package/services/go-sdk-generator.service.d.ts +26 -0
  45. package/services/go-sdk-generator.service.js +227 -0
  46. package/services/go-sdk-generator.service.js.map +1 -0
  47. package/services/protoc.service.d.ts +5 -0
  48. package/services/protoc.service.js +26 -0
  49. package/services/protoc.service.js.map +1 -0
  50. package/services/rust-sdk-generator.service.d.ts +24 -0
  51. package/services/rust-sdk-generator.service.js +201 -0
  52. package/services/rust-sdk-generator.service.js.map +1 -0
  53. package/services/sdk-descriptor.service.d.ts +13 -0
  54. package/services/sdk-descriptor.service.js +142 -0
  55. package/services/sdk-descriptor.service.js.map +1 -0
  56. package/templates/go/client.hbs +171 -0
  57. package/templates/go/enums.hbs +14 -0
  58. package/templates/go/errors.hbs +55 -0
  59. package/templates/go/go-mod.hbs +8 -0
  60. package/templates/rust/cargo-toml.hbs +13 -0
  61. package/templates/rust/client.hbs +100 -0
  62. package/templates/rust/enums.hbs +61 -0
  63. package/templates/rust/error.hbs +52 -0
  64. package/templates/rust/lib.hbs +17 -0
  65. package/types/sdk-build-config.type.d.ts +15 -0
  66. package/types/sdk-build-config.type.js +1 -1
  67. package/types/sdk-build-config.type.js.map +1 -1
  68. package/types/sdk-descriptor.type.d.ts +29 -0
  69. package/types/sdk-descriptor.type.js +2 -0
  70. package/types/sdk-descriptor.type.js.map +1 -0
@@ -0,0 +1,100 @@
1
+ // Generated by @hodfords/nestjs-grpc-helper. Do not edit.
2
+
3
+ use std::pin::Pin;
4
+ use std::time::Duration;
5
+
6
+ #[allow(unused_imports)]
7
+ use tokio_stream::{Stream, StreamExt};
8
+ use tonic::metadata::MetadataMap;
9
+ use tonic::transport::{Channel, Endpoint};
10
+
11
+ use crate::error::SdkError;
12
+ use crate::pb;
13
+
14
+ /// Typed server stream returned by streaming methods.
15
+ ///
16
+ /// A per-call timeout (`CallOptions.timeout`) bounds only the wait for the response to start (the
17
+ /// response headers), not the lifetime of the stream: once the stream is open it runs until the
18
+ /// server ends it or the stream is dropped.
19
+ pub type SdkStream<T> = Pin<Box<dyn Stream<Item = Result<T, SdkError>> + Send + 'static>>;
20
+
21
+ /// Options shared by every call of a client.
22
+ #[derive(Clone, Debug, Default)]
23
+ pub struct ClientOptions {
24
+ /// Default timeout of unary calls. Streams never use it.
25
+ pub timeout: Option<Duration>,
26
+ /// Largest response message, in bytes, the client accepts. `None` keeps tonic's default (4 MiB).
27
+ pub max_decoding_message_size: Option<usize>,
28
+ /// Largest request message, in bytes, the client sends. `None` keeps tonic's default (no limit).
29
+ pub max_encoding_message_size: Option<usize>,
30
+ }
31
+
32
+ /// Options of a single call.
33
+ #[derive(Clone, Debug, Default)]
34
+ pub struct CallOptions {
35
+ pub metadata: MetadataMap,
36
+ /// Overrides the client's default timeout. For a stream this is the only timeout applied, and it
37
+ /// bounds the wait for the response to start (headers), not the lifetime of the stream.
38
+ /// An expired timeout is reported as `DEADLINE_EXCEEDED`.
39
+ pub timeout: Option<Duration>,
40
+ }
41
+
42
+ fn build_request<T>(message: T, timeout: Option<Duration>, metadata: MetadataMap) -> tonic::Request<T> {
43
+ let mut request = tonic::Request::new(message);
44
+ // Metadata first: set_timeout stores the deadline in the request metadata.
45
+ *request.metadata_mut() = metadata;
46
+ if let Some(timeout) = timeout {
47
+ request.set_timeout(timeout);
48
+ }
49
+ request
50
+ }
51
+ {{#each services}}
52
+
53
+ {{#each docLines}}
54
+ /// {{{this}}}
55
+ {{/each}}
56
+ #[derive(Clone, Debug)]
57
+ pub struct {{clientName}} {
58
+ inner: pb::{{moduleName}}::{{clientName}}<Channel>,
59
+ options: ClientOptions,
60
+ }
61
+
62
+ impl {{clientName}} {
63
+ /// Connects to `url`, for example `http://localhost:50051`.
64
+ pub async fn connect(url: impl Into<String>, options: ClientOptions) -> Result<Self, SdkError> {
65
+ let channel = Endpoint::from_shared(url.into())?.connect().await?;
66
+ Ok(Self::new(channel, options))
67
+ }
68
+
69
+ /// Wraps an existing channel.
70
+ pub fn new(channel: Channel, options: ClientOptions) -> Self {
71
+ let mut inner = pb::{{moduleName}}::{{clientName}}::new(channel);
72
+ if let Some(limit) = options.max_decoding_message_size {
73
+ inner = inner.max_decoding_message_size(limit);
74
+ }
75
+ if let Some(limit) = options.max_encoding_message_size {
76
+ inner = inner.max_encoding_message_size(limit);
77
+ }
78
+ Self { inner, options }
79
+ }
80
+ {{#each methods}}
81
+
82
+ {{#each docLines}}
83
+ /// {{{this}}}
84
+ {{/each}}
85
+ {{#if isStream}}
86
+ pub async fn {{{fnName}}}(&self{{#if requestType}}, request: {{{requestType}}}{{/if}}, options: CallOptions) -> Result<SdkStream<{{{returnType}}}>, SdkError> {
87
+ let request = build_request({{{requestArg}}}, options.timeout, options.metadata);
88
+ let stream = self.inner.clone().{{{fnName}}}(request).await.map_err(SdkError::from_status)?.into_inner();
89
+ Ok(Box::pin(stream.map(|chunk| chunk.map(|response| {{{unwrapExpr}}}).map_err(SdkError::from_status))))
90
+ }
91
+ {{else}}
92
+ pub async fn {{{fnName}}}(&self{{#if requestType}}, request: {{{requestType}}}{{/if}}, options: CallOptions) -> Result<{{{returnType}}}, SdkError> {
93
+ let request = build_request({{{requestArg}}}, options.timeout.or(self.options.timeout), options.metadata);
94
+ let response = self.inner.clone().{{{fnName}}}(request).await.map_err(SdkError::from_status)?.into_inner();
95
+ Ok({{{unwrapExpr}}})
96
+ }
97
+ {{/if}}
98
+ {{/each}}
99
+ }
100
+ {{/each}}
@@ -0,0 +1,61 @@
1
+ // Generated by @hodfords/nestjs-grpc-helper. Do not edit.
2
+ //
3
+ // Allowed values of enum fields. The fields themselves keep their wire type (String or i32).
4
+ {{#each enums}}
5
+
6
+ #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
7
+ {{#if isNumber}}
8
+ #[repr(i32)]
9
+ pub enum {{rustName}} {
10
+ {{#each entries}}
11
+ {{variant}} = {{{literal}}},
12
+ {{/each}}
13
+ }
14
+
15
+ impl {{rustName}} {
16
+ pub const fn value(self) -> i32 {
17
+ self as i32
18
+ }
19
+
20
+ pub fn from_value(value: i32) -> Option<Self> {
21
+ match value {
22
+ {{#each entries}}
23
+ {{{literal}}} => Some(Self::{{variant}}),
24
+ {{/each}}
25
+ _ => None,
26
+ }
27
+ }
28
+ }
29
+ {{else}}
30
+ pub enum {{rustName}} {
31
+ {{#each entries}}
32
+ {{variant}},
33
+ {{/each}}
34
+ }
35
+
36
+ impl {{rustName}} {
37
+ pub const fn as_str(self) -> &'static str {
38
+ match self {
39
+ {{#each entries}}
40
+ Self::{{variant}} => {{{literal}}},
41
+ {{/each}}
42
+ }
43
+ }
44
+
45
+ pub fn from_value(value: &str) -> Option<Self> {
46
+ match value {
47
+ {{#each entries}}
48
+ {{{literal}}} => Some(Self::{{variant}}),
49
+ {{/each}}
50
+ _ => None,
51
+ }
52
+ }
53
+ }
54
+
55
+ impl std::fmt::Display for {{rustName}} {
56
+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
57
+ f.write_str(self.as_str())
58
+ }
59
+ }
60
+ {{/if}}
61
+ {{/each}}
@@ -0,0 +1,52 @@
1
+ // Generated by @hodfords/nestjs-grpc-helper. Do not edit.
2
+
3
+ /// Error returned by every SDK call.
4
+ #[derive(Debug, thiserror::Error)]
5
+ pub enum SdkError {
6
+ /// Business error. The server sends it as an ABORTED status whose message is the JSON object
7
+ /// `{ "message", "code", "errors" }`.
8
+ #[error("service error {code}: {message}")]
9
+ Service {
10
+ code: i64,
11
+ message: String,
12
+ errors: serde_json::Value,
13
+ },
14
+ /// Any other gRPC status, unchanged.
15
+ #[error(transparent)]
16
+ Status(tonic::Status),
17
+ /// Connection failure.
18
+ #[error(transparent)]
19
+ Transport(#[from] tonic::transport::Error),
20
+ }
21
+
22
+ impl SdkError {
23
+ pub fn from_status(status: tonic::Status) -> Self {
24
+ // tonic 0.12 enforces `Request::set_timeout` with a client-side timer and reports its expiry
25
+ // as CANCELLED with the message "Timeout expired". Report it as DEADLINE_EXCEEDED, like the
26
+ // server-side deadline and the Go SDK do.
27
+ if status.code() == tonic::Code::Cancelled && status.message() == "Timeout expired" {
28
+ return SdkError::Status(tonic::Status::deadline_exceeded("Timeout expired"));
29
+ }
30
+
31
+ if status.code() != tonic::Code::Aborted {
32
+ return SdkError::Status(status);
33
+ }
34
+
35
+ let payload = match serde_json::from_str::<serde_json::Value>(status.message()) {
36
+ Ok(serde_json::Value::Object(payload)) => payload,
37
+ _ => return SdkError::Status(status),
38
+ };
39
+
40
+ let message = match payload.get("message") {
41
+ Some(serde_json::Value::String(text)) => text.clone(),
42
+ Some(other) => other.to_string(),
43
+ None => String::new(),
44
+ };
45
+
46
+ SdkError::Service {
47
+ code: payload.get("code").and_then(serde_json::Value::as_i64).unwrap_or(0),
48
+ message,
49
+ errors: payload.get("errors").cloned().unwrap_or(serde_json::Value::Null),
50
+ }
51
+ }
52
+ }
@@ -0,0 +1,17 @@
1
+ //! Generated by @hodfords/nestjs-grpc-helper. Do not edit.
2
+
3
+ /// Messages and tonic stubs generated by protoc from `microservice.proto`.
4
+ #[allow(clippy::all, non_camel_case_types)]
5
+ pub mod pb {
6
+ include!("generated/{{{protoFile}}}");
7
+ {{#if includeTonicFile}}
8
+ include!("generated/{{{tonicFile}}}");
9
+ {{/if}}
10
+ }
11
+
12
+ pub mod client;
13
+ pub mod enums;
14
+ pub mod error;
15
+
16
+ pub use client::*;
17
+ pub use error::SdkError;
@@ -1,3 +1,16 @@
1
+ export declare const SDK_LANGUAGES: readonly ["ts", "rust", "go"];
2
+ export type SdkLanguage = (typeof SDK_LANGUAGES)[number];
3
+ export type RustSdkConfigType = {
4
+ crateName: string;
5
+ version?: string;
6
+ output: string;
7
+ build?: boolean;
8
+ };
9
+ export type GoSdkConfigType = {
10
+ module: string;
11
+ output: string;
12
+ build?: boolean;
13
+ };
1
14
  export type SdkBuildConfigType = {
2
15
  name: string;
3
16
  packageName: string;
@@ -13,4 +26,6 @@ export type SdkBuildConfigType = {
13
26
  outputBuild?: string;
14
27
  removeOutput?: boolean;
15
28
  tsconfig?: any;
29
+ rust?: RustSdkConfigType;
30
+ go?: GoSdkConfigType;
16
31
  };
@@ -1,2 +1,2 @@
1
- export {};
1
+ export const SDK_LANGUAGES = ['ts', 'rust', 'go'];
2
2
  //# sourceMappingURL=sdk-build-config.type.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"sdk-build-config.type.js","sourceRoot":"","sources":["../../../lib/types/sdk-build-config.type.ts"],"names":[],"mappings":""}
1
+ {"version":3,"file":"sdk-build-config.type.js","sourceRoot":"","sources":["../../../lib/types/sdk-build-config.type.ts"],"names":[],"mappings":"AAAA,MAAM,CAAC,MAAM,aAAa,GAAG,CAAC,IAAI,EAAE,MAAM,EAAE,IAAI,CAAU,CAAC"}
@@ -0,0 +1,29 @@
1
+ export type SdkNativeType = 'string' | 'bool' | 'float';
2
+ export type SdkResponseKind = 'empty' | 'single' | 'list' | 'native' | 'nativeList' | 'nullable' | 'nullableNative';
3
+ export type SdkMethodDescriptor = {
4
+ name: string;
5
+ description?: string;
6
+ requestType?: string;
7
+ responseKind: SdkResponseKind;
8
+ responseType?: string;
9
+ wireResponseType: string;
10
+ isStream: boolean;
11
+ metadataKeys: string[];
12
+ };
13
+ export type SdkServiceDescriptor = {
14
+ name: string;
15
+ description?: string;
16
+ methods: SdkMethodDescriptor[];
17
+ };
18
+ export type SdkEnumDescriptor = {
19
+ name: string;
20
+ valueType: 'string' | 'number';
21
+ entries: {
22
+ key: string;
23
+ value: string | number;
24
+ }[];
25
+ };
26
+ export type SdkDescriptor = {
27
+ services: SdkServiceDescriptor[];
28
+ enums: SdkEnumDescriptor[];
29
+ };
@@ -0,0 +1,2 @@
1
+ export {};
2
+ //# sourceMappingURL=sdk-descriptor.type.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"sdk-descriptor.type.js","sourceRoot":"","sources":["../../../lib/types/sdk-descriptor.type.ts"],"names":[],"mappings":""}