TypeScript (Node)

Install

First things first, let’s install the TypeScript library!

(If you already installed the VSCode extension, the extension setup may have already installed the library.)

Run this command to ensure the TypeScript library is installed:

$ npm install polyapi

Important

PolyAPI requires Node JS 14.0.0 or higher and TypeScript 4.0.0 or higher.

Setup and Generate

First configure your client:

$ npx poly setup

Enter your server and API Key when prompted.

Note

This command will also request for you to install/update some dependencies like ts-node and TypeScript.

Next, let’s go ahead and retrieve all the trained Poly functions and generate the TypeScript SDK for them:

$ npx poly generate

Warning

Please be sure to add node_modules to your .gitignore file.

Not only is it good practice in general, with PolyAPI your api key is stored in node_modules/.poly/.config.env so you can quickly run npx poly generate (and other commands) without having to re-enter your api key each time.

So be sure to add node_modules to your .gitignore file to avoid accidentally committing your api key to your git repo.

Develop First Function

Next, let’s develop our first custom function!

Open a new file called hello-world.ts and add the following code:

function helloWorld(): string {
    return 'Hello Poly World!';
}

Next use the PolyAPI TypeScript SDK to deploy this function:

$ npx poly function add helloWorld ./hello-world.ts --context "myContext" --server

This will deploy a new serverless function to Poly. You can also use –client option to create functions which are packaged into the generated SDK.

Run First Function

Finally, let’s open a new file called index.ts and add the following code:

import poly from 'polyapi';

(async () => {
    console.log(await poly.myContext.helloWorld());
})();

Now run your file:

$ npx ts-node ./index.ts

The function will run and you should see “Hello Poly World!” printed in the console.

Glide Farther

Deploying one-off functions this way is fine, but it won’t necessarily scale with more functions or if we have a team of people writing and deploying these functions.

To make building and deploying even easier, we’ve put together Project Glide, which lets you integrate PolyAPI more deeply into your git-based workflow backed by Github.

With a pre-commit hook in git, we can write functions and Poly will detect them automatically, validate them, and document them before we commit them.

And then once committed, the PolyAPI deployment action on Github picks up all our functions and deploys them to Poly.

See documentation in Project Glide to learn more and to setup this workflow.

Onward

That’s it! You have now:

  • Setup your Typescript SDK

  • Trained your first server function

  • Ran your first server function

This is the last step on the guided tour of Poly.

To further explore aspects of Poly and what it can do, head over to Next Steps.