简体   繁体   English

在 nodejs 运行时使用 Javascript 编译 Elm function

[英]Using Javascript compiled Elm function inside nodejs runtime

Okay so I'm using MongoDB Realm functions, a serverless platform that you define your functions like this:好的,所以我正在使用 MongoDB Realm 函数,一个无服务器平台,您可以像这样定义函数:

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?我想问是否可以在 Elm function 中编码并在 nodejs 运行时中运行它? 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
};

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.首先,您需要使用Platform.worker设置您的 Elm 文件——这基本上是一个无头 Elm 程序。

You would typically pass input that you have available synchronously ( param1 and param2 in your example) as flags.您通常会将同步可用的输入(在您的示例中为param1param2 )作为标志传递。 You would then define an output port that you would call from your Elm program when it completes.然后,您将定义一个 output 端口,您将在 Elm 程序完成时调用该端口。 On the JS side you would handle it like this:在 JS 方面,你会像这样处理它:

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): Elm 代码可能如下所示(假设您的代码是纯代码):

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"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM