question

newuser-0d689f45-f9da-47fc-9211-0a73456da6ad avatar image
newuser-0d689f45-f9da-47fc-9211-0a73456da6ad asked ·

Best practice for reusing code in APL

Hey,

I have a custom object in my apl templates which is copied to every apl template, resulting in a lot of duplicate code. Is there a good and easy way of reusing apl elements, other than hosting it on S3 and importing it?
I'm looking for a solution to have all my code in my project, not hosting parts of it on S3.


Thank you in advance :)

Kind regards,

Peter

alexa skills kitalexaaplask sdk
10 |2000 characters needed characters left characters exceeded

Up to 2 attachments (including images) can be used with a maximum of 512.0 KiB each and 1.0 MiB total.

1 Answer

Alexander Martin avatar image
Alexander Martin answered ·

Hi Peter,

if you don't want to use the import functionality you can do it this way:

You create a shared.json file that contains everything you want to share between your documents, in your index.js you simply merge the files (shared.json and for example template.json) (i used the merge function of lodash for this) The result (document) of the merge can be passed to your directive afterwards.

shared.json

{
  "layouts": {
    "Foo": {
      "item": {
        "type": "Text",
        "text": "Shared"
      }
    }
  }
}

template.json

{
  "type": "APL",
  "version": "1.5",
  "layouts": {
    "Bar": {
      "item": {
        "type": "Text",
        "text": "Template"
      }
    }
  },
  "mainTemplate": {
    "parameters": ["payload"],
    "items": [{
      "type": "Foo"
    }, {
      "type": "Bar"
    }]
  }
}

index.js

const shared = require('./shared.json');
const layout = require('./template.json');
const { merge } = require('lodash');
const document = merge(layout, shared);
console.log(JSON.stringify(document, undefined, 2));

output:

{
  "type": "APL",
  "version": "1.5",
  "layouts": {
    "Bar": {
      "item": {
        "type": "Text",
        "text": "Template"
      }
    },
    "Foo": {
      "item": {
        "type": "Text",
        "text": "Shared"
      }
    }
  },
  "mainTemplate": {
    "parameters": [
      "payload"
    ],
    "items": [
      {
        "type": "Foo"
      },
      {
        "type": "Bar"
      }
    ]
  }
}

Hope this helps.

Regards, Alex

10 |2000 characters needed characters left characters exceeded

Up to 2 attachments (including images) can be used with a maximum of 512.0 KiB each and 1.0 MiB total.