Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Javascript compiled Elm function inside nodejs runtime

Tags:

javascript

elm

Okay so I'm using MongoDB Realm functions, a serverless platform that you define your functions like this:

exports = async function(param1, param2){
   var result = {}
   // do stuff 
   return result;
}
if (typeof module === 'object') {
  module.exports = exports;
}

I want to ask if its possible to code in Elm function and run it inside a nodejs runtime? In other words like this:

exports = async function(param1, param2){
   var result = {}
   // do stuff 
   // call elm compiled js
   return elmFunction(param1, param2);
}
var elmFunction = async function(param1, param2) {
  // generator elm code
};
like image 519
Fireburn Avatar asked Jan 25 '23 10:01

Fireburn


1 Answers

Yes, but it can be a little tricky.

First, you need to setup your Elm file using Platform.worker - this basically a headless Elm program.

You would typically pass input that you have available synchronously (param1 and param2 in your example) as flags. You would then define an output port that you would call from your Elm program when it completes. On the JS side you would handle it like this:

exports = async function(param1, param2){
   const elmProgram = Elm.Main.init({flags: {param1, param2}});
   return new Promise((resolve) => {
     elmProgram.ports.outputPort.subscribe((result) => {
       resolve(result);
     });
   });
}

The Elm code might look like this (assuming your code is pure):

port module Main exposing (main)

import Json.Decode exposing (Value)
import Json.Encode

port outputPort : Value -> Cmd msg

main = 
    Platform.worker
        { init = init,
        , subscriptions = always Sub.none
        , update = \msg model -> (model, Cmd.none)
        }

init flags =
    case Json.Decode.decodeValue flagsDecoder flags of
        Ok input ->
            let
                 result = 
                      myFunction input 
            in
            ((), outputPort (resultEncoder result))
        
        Err e ->
            Debug.todo "error handling"
like image 146
Jakub Hampl Avatar answered Feb 13 '23 18:02

Jakub Hampl