Implementing custom type in Astronomy

I am using Astronomy package and want to implement Custom type. I have read the documentation and looked at examples of array_field.js and object_field.js, but still have hard time building a custom type Set. I want to have a support for Set object. I tried to use the code from array_field, but without much success. Actually it did store something in the document for that field, but it looks broken. I would also like to have Map custom type, i.e. a Map object. If someone can give some guidance on how to implement the following methods:

constructor: function Type(fieldDefinition) {},
getDefault: function(defaultValue) {},
cast: function(value) {},
needsCast: function(value) {},
plain: function(value) {},
needsPlain: function(value) {}

Just mention @jagi and you’ll get an answer directly from the Astronomy creator - he does an awesome job helping people out.

Hi, for simplicity you can omit the needsCast and the needsPlain methods. It’s just for performance improvements, but to just make it work first you can omit them. In fact we only have to focus on two functions: cast and plain.

Astro.createType({
  name: 'map',
  cast: function(entries) {
    var map = new Map();
    entires.forEach(function(value, key) {
      map.set(key, value);
    });
    return map;
  },
  plain: function(map) {
    var entries = {};
    map.forEach(function(value, key) {
      entries[key] = value;
    });
    return entries;
  }
}

I haven’t tested it but it should work. The plain method is called when you are converting a value to a format that will be stored in a database. And the cast method is called when a value is taken in plain format from the database and it needs to be casted to your type.

2 Likes

Thank you very much for this, @jagi. I just need to figure out some details with regards to casting issue. Will post more, when I figure it out.

Ok so just let me know what problem you have when you figure it out.