0

I have data coming from an external source that I want to process. In order to do that, the objects I'm receiving are tagged with their original class name. Now I want to take that tag name and use it to populate a model in my own application. I'm stuck at the step where I check for that class having an equivalent in my codebase. Its going to look something like this:

this.objects.forEach((object) => {

if (typeof object.class_tag !== 'undefined') { //the problem line
//create class instance
}

});

In php I'd simply call class_exists to achieve this

<?php
if (class_exists($object->class_tag)) {}

What is the correct approach here?

tracer tong
  • 543
  • 6
  • 16
  • How important is the type safety in your app? For example, does it *have* to be an instance of X class? Just thinking anonymous objects would be a lot easier here. – James Jul 27 '18 at 09:24
  • @James there is a requirement to treat data differently on a per model basis. That would be difficult in plain objects – tracer tong Jul 27 '18 at 09:35

2 Answers2

1

I don't see the clear way to do this in a just one line.

One of the possible approaches is the way you register your existing classes. For example if you use some kind of a namespace later on you can simply check the class for existance in the namespace. Sample code:

class A {}
const a = "A"
const namespace = { A };

if (namespace[a]) {
  // class exists, you can create object
  const instance = new namespace[a]();
}

Probably, much better approach would be to make some service, that will registerClass, checkClass and createInstance for you. So your logic is wrapped in one place.

Lazyexpert
  • 3,106
  • 1
  • 19
  • 33
  • For me, a service is the way to go here - there's no idiomatic way of doing this and I would say explicitness would be better to avoid any unexpected behaviour. – James Jul 27 '18 at 10:39
  • @James I would say, there is some architectural problem in the app, if TS has to do something like this. – Lazyexpert Jul 27 '18 at 11:43
0

I found a way of doing it

(credit to https://stackoverflow.com/a/34656123/746549)

let logger = require('../javascripts/serverlog');
let util = require('util');

let Extension = require('../models/object/Extension');

const classes = {Extension: Extension};

/**
 * Utility to emulate class exists / dynamic class naming
 * @param className
 * @returns {*}
 */
module.exports.dynamicClass = (className) => {

    logger.debug(classes);
    logger.debug(className);
    if (classes[className]) {
        return classes[className];
    } else {
        return false;
    }

};

Usage:

let ClassOrFalse = dynamicClass.dynamicClass(object._class_tag);
tracer tong
  • 543
  • 6
  • 16