node.jselixirphoenix-frameworkapple-walletpkpass

Call Typescript function from within an Phoenix / Elixir GET function


I am currently working within an Elixir / Phoenix project. I have some typescript code that I would like to run from within a GET function. What is the best practice for this?

To give more context, I need to dynamically create Apple pkpass files. The trouble is, creation of pkpass files is complicated, and there is no Elixir library to handle this creation, however there is a node.js package to handle this called https://github.com/walletpass/pass-js.

I have already built out a typescript class to handle the creation of the pkpass files, but I have no way to use this typescript class from my Phoenix project written in Elixir. How would one accomplish this?


Solution

  • Two popular options:

    1. Encapsulate your TypeScript class in a CLI wrapper and use it as a program

    2. Use something like Execjs or elixir-nodejs

    Considering the complexity of pass-js and how to configure it, I would definitely recommend you start with the first approach.

    Develop the command-line interface

    First, develop the CLI for your TS code. Suggestion: you should accept arguments, generate the file, and print the generated file path to the stdout.

    Here is a guide with the basics: https://walrus.ai/blog/2019/11/typescript-cli/

    Call your program!

    Then, call your program in Elixir using System.cmd/3.

    {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)
    

    The program interface is up to you. I advise you start simple.

    For instance, you could also return a JSON and parse it with Jason. Or you could print the binary file to stdout and read it directly, but there is additional complexity with this approach.