Sweet.apex

  • Docs
  • Tutorials
Docs Menu
  • Sweet.apex Core
    • Transpilation
    • Grammar
    • Command
    • Config
  • Features
    • Action
    • Apex Doc
    • Array Creation
    • Aspect
    • Cast
    • Default Value
    • Enum
    • File
    • Function
    • Identity
    • Injection
    • Lambda
    • Log
    • Mod
    • Not Null
    • Operator
    • Optional
    • Reflection
    • Rethrow
    • Switch
    • Template String
    • Template
    • Script
    • Tagged String
    • Annotation
    • Nullable
    • Var
    • Val
    • Map Access
    • Constructor
    • Transaction
    • Destructure
    • Import Static
    • Pipeline
    • Varargs
    • Patch
    • Import As
  • Plugin Development
    • Feature
    • Test Case

Script Guide

Script

Feature Overview

This feature generates javascript functions for Apex methods.

Prerequisite

None

Sweet Apex Example

public class ScriptDemo {
    /**
     * Some comments
     * */
    @script
    public static Integer add(Integer a, Integer b) {
        return a + b;
    }

    @script
    public static String env() {
        /* @script
          return 'script';
         */
        return 'apex';
    }
}

Transpiled Apex

public class ScriptDemo {
    /**
     * Some comments
     * */
    public static Integer add(Integer a, Integer b) {
        return a + b;
    }
    public static String env() {
        /* @script
          return 'script';
         */
        return 'apex';
    }
}

Generated JavaScript

The script is generated by the name sweetApp.js in the script directory set in the config.

;;
(function() {
    

    const ScriptDemo = {};

    /**
     * Some comments
     * */
    const ScriptDemo_add = function add(a, b) {
        return a + b;
    }
    const ScriptDemo_env = function env() {
        return 'script';
    }

    ScriptDemo.add = ScriptDemo_add;
    ScriptDemo.env = ScriptDemo_env;

    const $SweetApp = {};
    $SweetApp.ScriptDemo = ScriptDemo;
    window.$SweetApp = $SweetApp;
})();

Usage

@script can only be used on public/global static methods.

The main purpose of this feature is to generate both JavaScript code and Apex code that produce the same result, so that the same business logic can be applied both front end and back end.

A @script function can be in either form:

  • Native Script Form

Besides the @script, you need to add a comment including the javascript implementation of this method, like env() in the example, inside your Apex method. This way Sweet.apex will use the native javascript code to generate the javascript function.

  • Interpreted Form

You only need the @script and Sweet.apex will transpile your Apex code to javascript code.

Note that Sweet.apex only transpiles the direct Apex method, not including any nested method calls. So if you call any other Apex methods, make sure that they are also @script methods.

Contribute on Github! Edit this section.