5

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
};
0

1 Answer 1

9

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"
Sign up to request clarification or add additional context in comments.

2 Comments

In my idea, each method would be independent of each other even independent of database access, all methods would be functional and that can be unit tested independently
You can generalise this to call multiple functions in your Elm code. Simply pass the name of the function to call, decode it to the function you want to call, apply it and encode the result.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.