Skip to content

Commit

Permalink
docs: add javascript marshaling example (#635)
Browse files Browse the repository at this point in the history
  • Loading branch information
Samridhi-98 authored Feb 14, 2022
1 parent 594e7f1 commit 5567586
Show file tree
Hide file tree
Showing 8 changed files with 146 additions and 1 deletion.
12 changes: 11 additions & 1 deletion docs/languages/JavaScript.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ There are special use-cases that each language supports; this document pertains
<!-- toc -->

- [Rendering complete models to a specific module system](#rendering-complete-models-to-a-specific-module-system)
- [Generate un/marshal functions for classes](#generate-unmarshal-functions-for-classes)

<!-- tocstop -->

Expand All @@ -14,4 +15,13 @@ In some cases you might need to render the complete models to a specific module

Check out this [example for a live demonstration how to generate the complete JavaScript models to use ESM module system](../../examples/javascript-use-esm).

Check out this [example for a live demonstration how to generate the complete JavaScript models to use CJS module system](../../examples/javascript-use-cjs).
Check out this [example for a live demonstration how to generate the complete JavaScript models to use CJS module system](../../examples/javascript-use-cjs).


## Generate un/marshal functions for classes

Sometimes you want to use the models for data transfers, and while most cases would work out of the box, custom serializer functionality is needed for the advanced cases. If you generated the data models based on a JSON Schema document and you want the serialized data to validate against the schema, this functionality is REQUIRED.

Here, this can be done by including the preset `JS_COMMON_PRESET` using the option `marshalling`.

Check out this [example out for a live demonstration](../../examples/javascript-generate-marshalling).
1 change: 1 addition & 0 deletions examples/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ This directory contains a series of self-contained examples that you can use as
- [generate-javascript-models](./generate-javascript-models) - A basic example to generate JavaScript data models
- [javascript-use-esm](./javascript-use-esm) - A basic example that generate the models to use ESM module system.
- [javascript-use-cjs](./javascript-use-cjs) - A basic example that generate the models to use CJS module system.
- [javascript-generate-marshalling](./javascript-generate-marshalling) - A basic example of how to use the un/marshalling functionality of the javascript class.
- [generate-java-models](./generate-java-models) - A basic example to generate Java data models.
- [generate-go-models](./generate-go-models) - A basic example to generate Go data models
- [include-custom-function](./include-custom-function) - A basic example where a custom function is included.
Expand Down
17 changes: 17 additions & 0 deletions examples/javascript-generate-marshalling/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
# JavaScript Data Models with un/marshalling functionality

A basic example of how to use the un/marshalling functionality of the javascript class.

## How to run this example

Run this example using:

```sh
npm i && npm run start
```

If you are on Windows, use the `start:windows` script instead:

```sh
npm i && npm run start:windows
```
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
// Jest Snapshot v1, https://goo.gl/fbAQLP

exports[`Should be able to generate ts data model with marshal und unmarshal functions and should log expected output to console 1`] = `
Array [
"class Test {
email;
constructor(input) {
if (input.hasOwnProperty('email')) {
this.email = input.email;
}
}
get email() { return this.email; }
set email(email) { this.email = email; }
marshal(){
let json = '{'
if(this.email !== undefined) {
json += \`\\"email\\": \${typeof this.email === 'number' || typeof this.email === 'boolean' ? this.email : JSON.stringify(this.email)},\`;
}
//Remove potential last comma
return \`\${json.charAt(json.length-1) === ',' ? json.slice(0, json.length-1) : json}}\`;
}
unmarshal(json){
const obj = typeof json === \\"object\\" ? json : JSON.parse(json);
const instance = new Test({});
if (obj[\\"email\\"] !== undefined) {
instance.email = obj[\\"email\\"];
}
//Not part of core properties
for (const [key, value] of Object.entries(obj).filter((([key,]) => {return ![\\"email\\"].includes(key);}))) {
}
return instance;
}
}",
]
`;
14 changes: 14 additions & 0 deletions examples/javascript-generate-marshalling/index.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
const spy = jest.spyOn(global.console, 'log').mockImplementation(() => { return; });
import { generate } from './index';

describe('Should be able to generate ts data model with marshal und unmarshal functions', () => {
afterAll(() => {
jest.restoreAllMocks();
});
test('and should log expected output to console', async () => {
await generate();
//Generate is called 2x, so even though we expect 1 model, we double it
expect(spy.mock.calls.length).toEqual(2);
expect(spy.mock.calls[1]).toMatchSnapshot();
});
});
33 changes: 33 additions & 0 deletions examples/javascript-generate-marshalling/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
import { JavaScriptGenerator } from '../../src';
import { JS_COMMON_PRESET } from '../../src';

const generator = new JavaScriptGenerator({
presets: [
{
preset: JS_COMMON_PRESET,
options: {
marshalling: true
}
}
]
});
const jsonSchemaDraft7 = {
$schema: 'http://json-schema.org/draft-07/schema#',
$id: 'Test',
type: 'object',
additionalProperties: false,
properties: {
email: {
type: 'string',
format: 'email'
}
}
};

export async function generate(): Promise<void> {
const models = await generator.generate(jsonSchemaDraft7);
for (const model of models) {
console.log(model.result);
}
}
generate();
10 changes: 10 additions & 0 deletions examples/javascript-generate-marshalling/package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

12 changes: 12 additions & 0 deletions examples/javascript-generate-marshalling/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
{
"config": {
"example_name": "javascript-generate-marshalling"
},
"scripts": {
"install": "cd ../.. && npm i",
"start": "../../node_modules/.bin/ts-node --cwd ../../ ./examples/$npm_package_config_example_name/index.ts",
"start:windows": "..\\..\\node_modules\\.bin\\ts-node --cwd ..\\..\\ .\\examples\\%npm_package_config_example_name%\\index.ts",
"test": "../../node_modules/.bin/jest --config=../../jest.config.js ./examples/$npm_package_config_example_name/index.spec.ts",
"test:windows": "..\\..\\node_modules\\.bin\\jest --config=..\\..\\jest.config.js examples/%npm_package_config_example_name%/index.spec.ts"
}
}

0 comments on commit 5567586

Please sign in to comment.