首页 > 解决方案 > 从 Phoenix / Elixir GET 函数中调用 Typescript 函数

问题描述

我目前在 Elixir / Phoenix 项目中工作。我有一些我想在 GET 函数中运行的打字稿代码。对此的最佳做法是什么?

为了提供更多上下文,我需要动态创建 Apple pkpass 文件。麻烦的是,pkpass 文件的创建很复杂,并且没有 Elixir 库来处理这个创建,但是有一个 node.js 包来处理这个,叫做https://github.com/walletpass/pass-js

我已经构建了一个 typescript 类来处理 pkpass 文件的创建,但是我无法使用我用 Elixir 编写的 Phoenix 项目中的这个 typescript 类。一个人将如何做到这一点?

标签: node.jselixirphoenix-frameworkapple-walletpkpass

解决方案


两种流行的选择:

  1. 将您的 TypeScript 类封装在 CLI 包装器中并将其用作程序

  2. 使用类似Execjselixir-nodejs

考虑到它的复杂性pass-js以及如何配置它,我绝对建议您从第一种方法开始。

开发命令行界面

首先,为您的 TS 代码开发 CLI。建议:您应该接受参数,生成文件,并将生成的文件路径打印到stdout.

这是基础指南:https ://walrus.ai/blog/2019/11/typescript-cli/

调用你的程序!

然后,使用System.cmd/3在 Elixir 中调用您的程序。

{output, code} = System.cmd("/path/to/your/program", ["program", "arguments"])
file_path = String.trim(output)

# file_path is the path of the generated pkpass
# (if you print the generated file path to stdout)
#
# code is the exit code of the program.
# 0 means success, anything else means error (you should develop that in your CLI interface)

程序界面由您决定。我建议你从简单的开始。

例如,您还可以返回 JSON 并使用Jason对其进行解析。或者您可以将二进制文件打印到标准输出并直接读取它,但这种方法有额外的复杂性。


推荐阅读