@trayio/cdk-dsl 0.1.0 → 0.3.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 (2) hide show
  1. package/README.md +362 -0
  2. package/package.json +1 -1
package/README.md ADDED
@@ -0,0 +1,362 @@
1
+ # Connector Development Kit (CDK) DSL
2
+
3
+ The CDK Domain Specific Language (DSL) is the main component of Tray's CDK, it is used to define all the aspects of a connectors, including the behaviour of its operations.
4
+
5
+ A CDK connector consists of code written only using the DSL, which is declarative, so it only describes the connector, that description is then interpreted by the runtime
6
+ to execute a connector's operations.
7
+
8
+
9
+ ## Project Structure
10
+
11
+ A CDK project is just a regular npm typescript project, preconfigured with all the dependencies, linter rules and compiler options that will be used to build the connector during deployment, so it is not recommended to change those.
12
+
13
+ Other than the package.json, jest configuration and typescript configuration, a connector will have the following:
14
+
15
+ - A `connector.json` file that includes metadata about the connector, such as the name, version, title, etc
16
+ - A `src` directory that has:
17
+ - An Authentication typescript file that contains the type of the `auth` object that operations receive together with the input, this type is the same for all operation
18
+ - A `test.auth.json` json file that contains an auth value that can be used for tests.
19
+ **This file should not be committed to a repository as it will have sensitive information such as access tokens**
20
+ - One folder per operation
21
+
22
+ ## Authentications
23
+
24
+ Authentication values are received by operations together with the input, they usually contain things like tokens to identify the user making the request to a third party service.
25
+
26
+ Not all connectors need authentications, in that case, an empty type can be used (with an empty value in the authentication test file), which is what the init command generates by default.
27
+
28
+ ## Operations
29
+
30
+ A connector will have one folder per operation under the `src` folder, this folder will contain the following files:
31
+
32
+ - `input.ts` which contains the type of the input of the operation
33
+ - `output.ts` which contains the type of the output of the operation
34
+ - `handler.ts` which is where the logic of the operation is
35
+ - `handler.test.ts` which contains the test cases for testing the operation's behaviour defined in the handler
36
+
37
+ ## Handler
38
+
39
+ A handler at its core, describes a function, that takes an `auth` value described by the authentication type (which is the same for all operations) and it takes an `input` value described by the input type of the operation
40
+
41
+ The output of the handler is described by the output type, in case of a success, or it could contain an error if something failed during the execution of the handler or if the third party returned an error response.
42
+
43
+ This "successful value or failure error" result of running an operation is described by the `OperationHandlerResult<T>` type, which is a sum/union/or type of `OperationHandlerSuccess<T>` and `OperationHandlerFailure`
44
+
45
+ So, the core of what an operation handler describes can be summarised as a function:
46
+
47
+ ```typescript
48
+ (auth: AuthType, input: InputType) => OperationHandlerResult<OutputType>
49
+ ```
50
+
51
+ However, when defining a handler, we can also specify things like validation or whether or not the handler is private, and this is where the DSL comes in.
52
+
53
+ The `handler.ts` file needs to define a handler using the `OperationHandlerSetup.configureHandler()` function, which allows for configuring all aspects of the handler by chaining function calls together for all the components of the handler.
54
+
55
+ The `OperationHandlerSetup.configureHandler()` function takes the operation name and a callback that is used to configure the handler, it looks like this:
56
+
57
+ ```typescript
58
+ export const myOperationHandler =
59
+ OperationHandlerSetup.configureHandler<AuthType, InputType, OutputType>('my_operation', (handler) =>
60
+ /* use the "handler" value to specify what implementation to use, validation, etc */
61
+ );
62
+ ```
63
+
64
+ ## Validation
65
+
66
+ Handlers can have input validation (which runs before the handler implementation is executed to validate the input that will be used to run it) and output validation (which runs after the implementation to validate its output).
67
+
68
+ To add validation just use the `handler` argument of the callback described in the previous section:
69
+
70
+ ```typescript
71
+ export const myOperationHandler =
72
+ OperationHandlerSetup.configureHandler<AuthType, InputType, OutputType>('my_operation', (handler) =>
73
+ handler.addInputValidation((validation =>
74
+ validation.condition((auth, input) => input.id > 0)
75
+ .errorMessage((auth, input) => `Id ${input.id} is not positive`))
76
+ )
77
+ .addOutputValidation((validation =>
78
+ validation.condition((auth, input, output) => output.id === input.id)
79
+ .errorMessage((auth, input, output) => `Output and Input ids don't match`))
80
+ )
81
+ );
82
+ ```
83
+
84
+ Note that validation is optional, the only thing that is necessary to define a handler is its implementation.
85
+
86
+ ## Implementation
87
+
88
+ The main aspect of a handler is its implementation, which can be `HTTP` if the operation will make an HTTP call to a third party, or `Composite` if the operation will combine zero or more operations when it runs, more implementations for other protocols will be added in the future.
89
+
90
+ A handler can only have one implementation, it describes what the handler does when it receives a request.
91
+
92
+ ## HTTP Implementation
93
+
94
+ A very simple handler that makes an HTTP call can be configured in the following way:
95
+
96
+ ```typescript
97
+ export const myOperationHandler =
98
+ OperationHandlerSetup.configureHandler<AuthType, InputType, OutputType>('my_operation', (handler) =>
99
+ handler.addInputValidation(...)
100
+ .addOutputValidation(...)
101
+ .usingHttp((http) =>
102
+ http.get('https://someapi.com/someresource/:id')
103
+ .handleRequest((auth, input, request) =>
104
+ request.addPathParameter('id', input.id.toString())
105
+ )
106
+ .handleResponse((response) => response.withBodyAsJson())
107
+ )
108
+ );
109
+ ```
110
+
111
+ The previous handler makes a `GET` http request, which is defined by the `http.get()` call, after which a `handleRequest()` function is chained, whose purpose is to take an auth value, an input value and a request configuration and add the necessary arguments to that request configuration based on what we want the http call to have, the supported methods on the request configuration are:
112
+
113
+ - `addPathParameter(name, value)`: Will replace a parameter on the path specified as `:name` in the url as shown in the previous example, the value will be url encoded
114
+ - `addHeader(name, value)`: Adds a header to the request
115
+ - `withBearerToken(token)`: Adds an `Authorization` header with a `Bearer` token
116
+ - `addQueryString(name, value)`: Adds a query string to the request, the value will be url encoded
117
+ - `withBodyAsJson(body)`: Adds a body to the request that will be sent as json.
118
+
119
+
120
+ A handler with an authenticated POST request would look like this:
121
+
122
+ ```typescript
123
+ export const myOperationHandler =
124
+ OperationHandlerSetup.configureHandler<AuthType, InputType, OutputType>('my_operation', (handler) =>
125
+ handler.addInputValidation(...)
126
+ .addOutputValidation(...)
127
+ .usingHttp((http) =>
128
+ http.post('https://someapi.com/someresource')
129
+ .handleRequest((auth, input, request) =>
130
+ request.withBearerToken(auth.access_token)
131
+ .withBodyAsJson(input)
132
+ )
133
+ .handleResponse((response) => response.withBodyAsJson())
134
+ )
135
+ );
136
+ ```
137
+
138
+ The input does not have to match what is sent as the body, if for example the input has other flags that specify how the connector needs to behave and only part of it contains the body, the `withBodyAsJson` method can be called in the following way:
139
+
140
+ ```typescript
141
+ request.withBodyAsJson({name: input.name, title: input.title})
142
+ ```
143
+
144
+ So the `handlerRequest` function can transform the input in any way it needs to before sending the HTTP request and the same is true for the `handleResponse`, in the previous examples, the `handleResponse` simply read the response body as json and returned it, but it can be more complex if necessary.
145
+
146
+ The `withBodyAsJson<T>()` function on the `response` argument returns a value of type `OperationHandlerResult<T>`, which can be a successful response or a failure based on the status code or if something went wrong executing the call.
147
+
148
+ Just like with the input type and the request, the type of the json body in the response can be different from the output type.
149
+
150
+ This is an example of a handler that transforms the response body into the output type:
151
+
152
+ ```typescript
153
+ export const myOperationHandler =
154
+ OperationHandlerSetup.configureHandler<AuthType, InputType, OutputType>('my_operation', (handler) =>
155
+ handler.addInputValidation(...)
156
+ .addOutputValidation(...)
157
+ .usingHttp((http) =>
158
+ http.post('https://someapi.com/someresource')
159
+ .handleRequest(...)
160
+ .handleResponse((response) => {
161
+ const httpResponseBody = response.withBodyAsJson<{message: string}>()
162
+ if (httpResponseBody.isSuccess) {
163
+ const originalMessage = httpResponseBody.value.message
164
+ const extendedMessage = originalMessage + ' Extension'
165
+ return OperationHandlerResult.success({ message: extendedMessage })
166
+ }
167
+ return httpResponseBody
168
+ })
169
+ )
170
+ );
171
+ ```
172
+
173
+ Instead of using an `if` in the previous case, there is also a `OperationHandlerResult.map` function that can do the same with a callback.
174
+
175
+ The handler can also return successful responses for some failure cases or viceversa, this is an example of a handler that "recovers" from errors to always return a successful response:
176
+
177
+ ```typescript
178
+ export const myOperationHandler =
179
+ OperationHandlerSetup.configureHandler<AuthType, InputType, OutputType>('my_operation', (handler) =>
180
+ handler.addInputValidation(...)
181
+ .addOutputValidation(...)
182
+ .usingHttp((http) =>
183
+ http.post('https://someapi.com/someresource')
184
+ .handleRequest(...)
185
+ .handleResponse((response) => {
186
+ const httpResponseBody = response.withBodyAsJson()
187
+ if (httpResponseBody.isFailure) {
188
+ return OperationHandlerResult.success({ completed: false })
189
+ }
190
+ return OperationHandlerResult.success({ completed: true })
191
+ })
192
+ )
193
+ );
194
+ ```
195
+
196
+
197
+ ## Composite Implementation
198
+
199
+ Composite handlers are used to define behaviours by invoking zero or more operations as part of their behaviour.
200
+
201
+ They can be used to write "helper" connectors (such as those in Tray's builder), DDL operations or complex operations
202
+ like an "upsert" that combines more granular "read, create and update" operations.
203
+
204
+ A very simple composite handler, that just concatenates the `firstName` and `lastName` arguments it gets from the input into one string:
205
+
206
+ ```typescript
207
+ export const myOperationHandler =
208
+ OperationHandlerSetup.configureHandler<AuthType, InputType, OutputType>('my_operation', (handler) =>
209
+ handler.addInputValidation(...)
210
+ .addOutputValidation(...)
211
+ .usingComposite(async (auth, input, invoke) => {
212
+ const fullName = input.firstName + ' ' + input.lastName
213
+ return OperationHandlerResult.success({fullName: fullName})
214
+ })
215
+ );
216
+ ```
217
+
218
+ As an example of more complex behaviour, this handler reads a list of products using another operation and converts the result into a simple list of `{text: string, value: string}` pairs, this is known as a Dynamic Data List (DDL) operation used to help users select values as part of configuring workflows within the tray builder.
219
+
220
+
221
+ To do this, the handler needs to invoke the regular `getProducts` operation, this is accomplished by using the `invoke` functions that composite handlers have access to, and passing it a **handler reference** and an input (no need to pass the auth value as it will be passed automatically), the handler reference passed to the `invoke` function is the result of the `OperationHandlerSetup.configureHandler()` function, which is why they are saved into a constant and exported like this:
222
+
223
+ ```typescript
224
+ export const getProductsHandler =
225
+ OperationHandlerSetup.configureHandler<AuthType, GetProductsInput, GetProductsOutput>('get_products', (handler) =>
226
+ handler.usingHttp(...)
227
+ );
228
+ ```
229
+
230
+ The `getProductsHandler` constant contains the handler reference, which also has the input and output type information as part of its type, to make sure that when invoked or tested, only valid input and output values can be used.
231
+
232
+
233
+ With that in mind, this is what the DDL handler would look like:
234
+
235
+
236
+ ```typescript
237
+ export const getProductsDDLHandler =
238
+ OperationHandlerSetup.configureHandler<AuthType, GetProductsDDLInput, GetProductsDDLOutput>('get_products_ddl', (handler) =>
239
+ handler.usingComposite(async (auth, input, invoke) => {
240
+ const productListResult: OperationHandlerResult<GetProductsOutput> =
241
+ await invoke(getProductsHandler)({ storeId: input.storeId })
242
+ return OperationHandlerResult.map(
243
+ productListResult,
244
+ productList => productList.map(product => { text: product.title, value: product.id })
245
+ )
246
+ })
247
+ );
248
+ ```
249
+
250
+ There are several things to note about the handler, both the DDL handler and the `getProductsHandler` expect a `storeId` in the input to return a list of products for that store.
251
+
252
+ The `getProductsHandler` is invoked using the `invoke` function that composite handlers receive as an argument, passing the handler reference, and then calling the result as a function passing the input that handler expects, in this case, just an object with a `storeId`
253
+
254
+ The result of that invocation is of type `Promise<OperationHandlerResult<GetProductsOutput>>`, that is, a promise that has a value that is described by the invoked handler's output type, which is wrapped in the result object because it could be a successful invocation or a failure as described in previous sections.
255
+
256
+ The `await` keyword unwraps the promise, and we are left with a `OperationHandlerResult<GetProductsOutput>`, which forces the handler to deal with both the failure case as well as the success case.
257
+
258
+ There are multiple ways to do this
259
+ - Using `if` or `switch` statements to narrow down the type
260
+ - Using the `OperationHandlerResult.getSuccessfulValueOrFail()` function which unwraps the value if successful or terminates the function propagating the error if it is not
261
+ - As shown in the example, using the `OperationHandlerResult.map()` function.
262
+
263
+ Once the handler has access to the product list value, it just needs to convert each element to a `{text: string, value: string}` pair.
264
+
265
+ ## Testing
266
+
267
+ The CDK DSL has declarative testing functions to test a handler's behaviour, the tests are in the `handler.test.ts` file within the operation folder, which can have zero, one or many test cases for that given operation.
268
+
269
+ The `OperationHandlerTestSetup.configureHandlerTest()` function is used to describe a test, it takes a handler reference and a callback with an object used to configure the test, in a similar way handlers are configured.
270
+
271
+ This is what a very basic test looks like:
272
+
273
+ ```typescript
274
+ OperationHandlerTestSetup.configureHandlerTest(
275
+ myOperationHandler,
276
+ (handlerTest) =>
277
+ handlerTest
278
+ .usingAuth('test') //will use `test.auth.json` as the authentication value for all test cases
279
+ .nothingBeforeAll()
280
+ .testCase('should do something', (testCase) =>
281
+ testCase
282
+ .usingAuth('another') //optionally, a test case can define its own auth instead of using the default one defined for all tests
283
+ .givenNoContext()
284
+ .when(() => /* return an input that matches the input type */)
285
+ .then(({ output }) => {
286
+ /* output is OperationHandlerResult<T> where T is a value matching the output type */
287
+
288
+ //This will contain a value of type T if the operation was successful or the test will fail if not
289
+ const successValue = OperationHandlerResult.getSuccessfulValueOrFail(output)
290
+
291
+ // jest-style matchers like "expect" are available here
292
+ expect(successValue).toEqual(...)
293
+ })
294
+ .finallyDoNothing()
295
+ )
296
+ .nothingAfterAll()
297
+ );
298
+ ```
299
+
300
+ The structure of a test is well defined, and the type safe declarative DSL will enforce that, in particular, there are a number of aspects that would apply to all test cases:
301
+
302
+ - A default authentication to use for all test cases
303
+ - Run one or more operations (doesn't have to be the one being tested) before all test cases using the `beforeAll()` function, or don't do anything before all test cases using the `nothingBeforeAll()` function, these functions can only be used before adding test cases (this is enforced by the type system)
304
+ - Add a test case using the `testCase()` function.
305
+ - Run one or more operations (doesn't have to be the one being tested) after all test cases using the `afterAll()` function, or don't do anything after all test cases using the `nothingAfterAll()` function, these functions can only be used after defining test cases, and no test cases can be added after this (this is enforced by the type system)
306
+
307
+
308
+ As for the test cases, they use a BDD style Given/When/Then convention, in particular a test case has:
309
+
310
+ - An optional `usingAuth()` function at the beginning of the test case to use a different auth than the default for all test cases
311
+ - A `given()` function to run one or more operations at the beginning of the test case or `givenNoContext()` to go straight to running the operation under test
312
+ - A `when()` function to create an input value that will be used to run the operation under test, that value needs to match the input type of the operation
313
+ - A `then()` function that gets the output, input, auth and optionally the result of `beforeAll()` and `given()` if present, which can be used to do the assertions of the test case using jest-style matchers
314
+ - A `finally()` function to run one or more operations at the end of the test case, usually for cleanup, or `finallyDoNothing()` to don't do anything else after the assertions.
315
+
316
+
317
+ Both the `beforeAll()` and `given()` functions allow to run multiple operations before all test cases or before a single test case, they receive the `invoke` function as an argument just like composite handlers and they return an object that can contain some of relevant information about the operations that ran if necessary (like ids of things created) in a value that can be accessed by the `when()`, `then()`, `finally()` and `afterAll()` functions, they receive them as arguments.
318
+
319
+ As an example, the following test is for an `updateProduct` operation, it creates a store for all test cases, and a product for every test case to test the update on, using `beforeAll` and `given` respectively, and accessing the identities of the created objects from the `testContext` (the output of `beforeAll`) and the `testCaseContext` (the output of `given`):
320
+
321
+ ```typescript
322
+ OperationHandlerTestSetup.configureHandlerTest(
323
+ updateProductOperationHandler,
324
+ (handlerTest) =>
325
+ handlerTest
326
+ .usingAuth('test')
327
+ .beforeAll<{storeId: string}>(async (auth, invoke) => {
328
+ //Creates an store that will be used by all tests
329
+ const createdStoreResult = invoke(createStoreHandler)({name: 'something'})
330
+ return OperationHandlerResult.map(
331
+ createdStoreResult,
332
+ createdStoreOutput => { storeId: createdStoreOutput.id}
333
+ )
334
+ })
335
+ .testCase('should do something', (testCase) =>
336
+ testCase
337
+ .given<{ productId: string}>((auth, testContext, invoke) => {
338
+ //Creates an product in the store to be used by the test
339
+ const createdProductResult = invoke(createProductHandler)({name: 'some product', storeId: testContext.storeId})
340
+ return OperationHandlerResult.map(
341
+ createdProductResult,
342
+ createdProductOutput => { productId: createdProductOutput.id}
343
+ )
344
+ })
345
+ .when((auth, testContext, testCaseContext) => ({ productId: testCaseContext.productId, name: 'updated name' }))
346
+ .then(({ output }) => {
347
+ const outputValue = OperationHandlerResult.getSuccessfulValueOrFail(output)
348
+ expect(outputValue.name).toEqual('updated name');
349
+ })
350
+ .finally(({ testCaseContext }) => {
351
+ //Deletes the product created for the test
352
+ return invoke(deleteProductHandler)({productId: testCaseContext.productId})
353
+ })
354
+ )
355
+ .afterAll(({ testContext }) => {
356
+ //Deletes the store created for all test cases
357
+ return invoke(deleteStoreHandler)({storeId: testContext.storeId})
358
+ })
359
+ );
360
+ ```
361
+
362
+ It is worth noting that while the DSL can be used to write complex functional tests, in practice, a connector test's focus is more about making sure that operations are properly communicating with the underlying implementation instead of testing its functionality, but ultimately it is up to the developer to decide how much and what type of coverage suits a given connector best.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@trayio/cdk-dsl",
3
- "version": "0.1.0",
3
+ "version": "0.3.0",
4
4
  "description": "A DSL for connector development",
5
5
  "exports": {
6
6
  "./*": "./dist/*.js"