Giter VIP home page Giter VIP logo

Comments (5)

alexdresko avatar alexdresko commented on August 26, 2024 1

Thanks for taking the time to respond. I hope someone else will find the information in this issue useful.

We use classes in TypeScript.

Our tsconfig.json looks like this:

{
  "compileOnSave": false,
  "compilerOptions": {
    "module": "esnext",
    "skipLibCheck": true,
    "removeComments": true,
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "sourceMap": true,
    "target": "es6",
    "lib": [
      "es2016",
      "dom"
    ],
    "moduleResolution": "node",
    "allowJs": true,
    "baseUrl": "src"
  },
  "include": [
    "./src/**/*.ts",
    "./test/**/*.ts",
    "./types/**/*.d.ts"
  ],
  "atom": {
    "rewriteTsconfig": false
  },
  "exclude": [
    "wwwroot/dist",
    "src/lib/jqGrid"
  ]
}

...and the relevant compiled .js looks like this:

export class SettingDto {
    constructor(data) {
        if (data) {
            for (var property in data) {
                if (data.hasOwnProperty(property))
                    this[property] = data[property];
            }
        }
    }
    init(data, _mappings) {
        if (data) {
            this.id = data["id"];
            this.createdOn = data["createdOn"] ? moment.parseZone(data["createdOn"].toString()) : undefined;
            this.modifiedOn = data["modifiedOn"] ? moment.parseZone(data["modifiedOn"].toString()) : undefined;
            this.createdBy = data["createdBy"];
            this.modifiedBy = data["modifiedBy"];
            this.version = data["version"];
            this.uiHint = data["uiHint"];
            this.label = data["label"];
            this.stringValue = data["stringValue"];
            this.intValue = data["intValue"];
            this.doubleValue = data["doubleValue"];
            this.decimalValue = data["decimalValue"];
            this.boolValue = data["boolValue"];
            this.dateTimeValue = data["dateTimeValue"] ? moment.parseZone(data["dateTimeValue"].toString()) : undefined;
            this.format = data["format"];
            this.listValues = data["listValues"];
            this.regexValidation = data["regexValidation"];
            this.name = data["name"];
            this.description = data["description"];
        }
    }
    static fromJS(data, _mappings) {
        data = typeof data === 'object' ? data : {};
        return createInstance(data, _mappings, SettingDto);
    }
    toJSON(data) {
        data = typeof data === 'object' ? data : {};
        data["id"] = this.id;
        data["createdOn"] = this.createdOn ? this.createdOn.toISOString(true) : undefined;
        data["modifiedOn"] = this.modifiedOn ? this.modifiedOn.toISOString(true) : undefined;
        data["createdBy"] = this.createdBy;
        data["modifiedBy"] = this.modifiedBy;
        data["version"] = this.version;
        data["uiHint"] = this.uiHint;
        data["label"] = this.label;
        data["stringValue"] = this.stringValue;
        data["intValue"] = this.intValue;
        data["doubleValue"] = this.doubleValue;
        data["decimalValue"] = this.decimalValue;
        data["boolValue"] = this.boolValue;
        data["dateTimeValue"] = this.dateTimeValue ? this.dateTimeValue.toISOString(true) : undefined;
        data["format"] = this.format;
        data["listValues"] = this.listValues;
        data["regexValidation"] = this.regexValidation;
        data["name"] = this.name;
        data["description"] = this.description;
        return data;
    }
}
export class CreateOrUpdateSettingDto {
    constructor(data) {
        if (data) {
            for (var property in data) {
                if (data.hasOwnProperty(property))
                    this[property] = data[property];
            }
        }
    }
    init(data, _mappings) {
        if (data) {
            this.uiHint = data["uiHint"];
            this.label = data["label"];
            this.stringValue = data["stringValue"];
            this.intValue = data["intValue"];
            this.doubleValue = data["doubleValue"];
            this.decimalValue = data["decimalValue"];
            this.boolValue = data["boolValue"];
            this.dateTimeValue = data["dateTimeValue"] ? moment.parseZone(data["dateTimeValue"].toString()) : undefined;
            this.format = data["format"];
            this.listValues = data["listValues"];
            this.regexValidation = data["regexValidation"];
            this.name = data["name"];
            this.description = data["description"];
        }
    }
    static fromJS(data, _mappings) {
        data = typeof data === 'object' ? data : {};
        return createInstance(data, _mappings, CreateOrUpdateSettingDto);
    }
    toJSON(data) {
        data = typeof data === 'object' ? data : {};
        data["uiHint"] = this.uiHint;
        data["label"] = this.label;
        data["stringValue"] = this.stringValue;
        data["intValue"] = this.intValue;
        data["doubleValue"] = this.doubleValue;
        data["decimalValue"] = this.decimalValue;
        data["boolValue"] = this.boolValue;
        data["dateTimeValue"] = this.dateTimeValue ? this.dateTimeValue.toISOString(true) : undefined;
        data["format"] = this.format;
        data["listValues"] = this.listValues;
        data["regexValidation"] = this.regexValidation;
        data["name"] = this.name;
        data["description"] = this.description;
        return data;
    }
}

Of course, it all gets webpack'd down to some kind of magic ninja code, but I'm pretty sure the classes stay classes at that level,

from morphism.

jcford73 avatar jcford73 commented on August 26, 2024 1

@emyann Can you provide an example of creating a schema that does automatic property mapping? I can't find one in the documentation.

from morphism.

emyann avatar emyann commented on August 26, 2024

@alexdresko Thank you for trying Morphism! Yes you can do something similar, depending on wether you're using ES6 Class objects or javascript plain objects as targets you'll benefit in the first case of automatic mapping of fields of the same name (same name in source and target) and in the second case, whatever mapping specified in the schema will be respected.
Can you share the definition of Setting, SettingDto, CreateOrUpdateSettingDto and let me know if you're using ES6 Classes or JS Objects ?

Thanks!

from morphism.

emyann avatar emyann commented on August 26, 2024

@alexdresko Sorry for the delay, busy week. Thank you for having provided your type definitions.
@jcford73 Please follow this link to see a working example of automatic property mapping: https://repl.it/@yrnd1/Morphism-Automatic-Property-Mapping-ES6-Class

Screen Shot 2019-06-21 at 11 10 36 AM

As you can see, you can skip the schema definition (also can be null instead of an empty object) and you'll have the properties of the same name automatically mapped from the source to the target.

I didn't really wanted to expose that feature because people should be aware that class properties should be strictly initialized so that Morphism can be find the keys in the target, because otherwise they won't be compiled down by Typescript (see the difference in TS Playground: https://bit.ly/2Y1gKcX)
(here's an old issue about this discussion #74)

I tend to prefer people to eagerly specify each transformations to avoid this kind of uncertainty and magic. But from what I understand, I should just document this and let people be aware of some of the gotchas with automatic mapping ?

Please let me know if you need further explanation, and I'll update the documentation accordingly.

Thanks!

from morphism.

emyann avatar emyann commented on August 26, 2024

@alexdresko Please find an example of automapping with your actual structure using ES6 Classes: https://repl.it/@yrnd1/Morphism-alexdresko-AutoMapping

import { morphism, Schema } from 'morphism'


class Setting {
  id?: string = undefined
  createdOn?: number = undefined
  modifiedOn?: number = undefined
  createdBy?: string = undefined
  modifiedBy?: string = undefined
  version?: string
  uiHint?: string = undefined
  label?: string = undefined
  stringValue?: string = undefined
  intValue?: string = undefined
  doubleValue?: string = undefined
  decimalValue?: string = undefined
  boolValue?: string = undefined
  dateTimeValue?: number
  format?: string = undefined
  listValues?: string = undefined
  regexValidation?: string = undefined
  name?: string = undefined
  description?: string = undefined
}

const schema : Schema<Setting> ={
  createdOn: ({createdOn})=> 1234 // overrides transformation with moment.parseZone for example
}

const toSetting = morphism(schema, null, Setting) // outputting a mapper

const source = {
  id: '1234',
  createdOn: 'createdOn-Value',
  modifiedOn: 'modifiedOn-Value',
  createdBy: 'createdBy-Value',
  modifiedBy: 'modifiedBy-Value',
  version: 'version-Value',
}
const setting = toSetting(source)
console.log(setting)
// ==>
// Setting {
//   id: '1234',
//   createdOn: 1234,
//   modifiedOn: 'modifiedOn-Value',
//   createdBy: 'createdBy-Value',
//   modifiedBy: 'modifiedBy-Value',
//   uiHint: undefined,
//   label: undefined,
//   stringValue: undefined,
//   intValue: undefined,
//   doubleValue: undefined,
//   decimalValue: undefined,
//   boolValue: undefined,
//   format: undefined,
//   listValues: undefined,
//   regexValidation: undefined,
//   name: undefined,
//   description: undefined }

I didn't specify all the properties in the source, but you should get the idea. I concede the default undefined values in the class is pretty ugly, but you should definitely initialize them if we want to find all the keys automatically :/
Also you can strip the undefined values with some options in the schema if it's necessary.

Feel free to ask questions about this example :)

from morphism.

Related Issues (20)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.