• Stars
    star
    628
  • Rank 71,541 (Top 2 %)
  • Language
    TypeScript
  • Created almost 6 years ago
  • Updated almost 2 years ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

TypeScript standard for rock solid serverless functions.
FTS Logo

Functional TypeScript

TypeScript standard for rock solid serverless functions. (sponsored by Saasify)

NPM Build Status JavaScript Style Guide

Features

  • Robust: Type-safe serverless functions!
  • Simple: Quick to setup and integrate
  • Standard: Just TypeScript + JSON Schema
  • Compatible: Supports all major serverless providers (AWS, GCP, Azure, Now, etc)
  • Explicit: Easily generate serverless function docs
  • Fast: Uses ajv for schema validation
  • Lightweight: Focused http handler optimized for serverless environments
  • Robust: Used in production at Saasify

Contents

What is Functional TypeScript (FTS)?

FTS transforms standard TypeScript functions like this:

/**
 * This is a basic TypeScript function.
 */
export function hello(name: string = 'World'): string {
  return `Hello ${name}!`
}

Into type-safe serverless functions that can be called over HTTP like this (GET):

https://example.com/hello?name=GitHub

Or like this (POST):

{
  "name": "GitHub"
}

And returns a result like this:

"Hello GitHub!"

All parameters and return values are type-checked by a standard Node.js HTTP handler, so you can invoke your TypeScript functions remotely with the same confidence as calling them directly.

Usage

You can use this package as either a CLI or as a module.

CLI

npm install -g fts

This will install the fts CLI program globally.

Generates an FTS Definition schema given a TS input file.

Usage: fts [options] <file.ts>

Options:
  -p, --project <project>  Path to 'tsconfig.json'.
  -h, --help               output usage information

Module

npm install --save fts

# (optional) add support for http transport
npm install --save fts-http

Here is an end-to-end example using HTTP (examples/hello-world).

const fts = require('fts')
const ftsHttp = require('fts-http')

async function example() {
  const tsFilePath = './hello-world.ts'
  const jsFilePath = './hello-world.js'

  // Parse a TS file's main function export into a Definition schema.
  const definition = await fts.generateDefinition(tsFilePath)
  console.log(JSON.stringify(definition, null, 2))

  // Create a standard http handler function `(req, res) => { ... }` that will
  // invoke the compiled JS function, performing type checking and conversions
  // between http and json for the function's parameters and return value.
  const handler = ftsHttp.createHttpHandler(definition, jsFilePath)

  // Create a `micro` http server that uses our HttpHandler to respond to
  // incoming http requests.
  await ftsHttp.createHttpServer(handler, 'http://localhost:3000')

  // You could alternatively use your `handler` with any Node.js server
  // framework, such as express, koa, @now/node, etc.
}

example().catch((err) => {
  console.error(err)
  process.exit(1)
})

Once you have a server running, you can invoke your type-safe function over HTTP:

$ curl -s 'http://localhost:3000?name=GET'
Hello GET!

$ curl -s 'http://localhost:3000' -d 'name=POST'
Hello POST!

Note that in this example, we're generating the FTS Definition and serving it together, but in practice we recommend that you generate these definitions during your build step, alongside your normal TS => JS compilation. The definitions should be viewed as json build artifacts that are referenced at runtime in your server or serverless function.

Definition Format

Given our "hello world" example from earlier, FTS generates the following JSON definition that fully specifies the hello function export.

{
  "title": "hello",
  "version": "0.0.1",
  "config": {
    "language": "typescript",
    "defaultExport": false,
    "namedExport": "hello"
  },
  "params": {
    "context": false,
    "order": ["name"],
    "schema": {
      "type": "object",
      "properties": {
        "name": {
          "type": "string",
          "default": "World"
        }
      },
      "additionalProperties": false,
      "required": ["name"],
      "$schema": "http://json-schema.org/draft-07/schema#"
    }
  },
  "returns": {
    "async": false,
    "schema": {
      "type": "object",
      "properties": {
        "result": {
          "type": "string"
        }
      },
      "$schema": "http://json-schema.org/draft-07/schema#"
    }
  }
}

In addition to some metadata, this definition contains a JSON Schema for the function's parameters and a JSON Schema for the function's return type.

Note that this definition allows for easy type checking, documentation generation, and automated testing via tools like json-schema-faker.

Status

FTS is stable and is actively used in production by Saasify.

FAQ

Why Serverless?

Serverless functions allow your code to run on-demand and scale automatically both infinitely upwards and down to zero. They are great at minimizing cost in terms of infrastructure and engineering time, largely due to removing operational overhead and reducing the surface area for potential errors.

For more information, see Why Serverless?, and an excellent breakdown on the Tradeoffs that come with Serverless.

Why FTS?

The serverless space has seen such rapid growth that tooling, especially across different cloud providers, has struggled to keep up. One of the major disadvantages of using serverless functions at the moment is that each cloud provider has their own conventions and gotchas, which can quickly lead to vendor lock-in.

For example, take the following Node.js serverless function defined across several cloud providers:

AWS

exports.handler = (event, context, callback) => {
  const name = event.name || 'World'
  callback(null, `Hello ${name}!`)
}

Azure

module.exports = function(context, req) {
  const name = req.query.name || (req.body && req.body.name) || 'World'
  context.res = { body: `Hello ${name}!` }
  context.done()
}

GCP

const escapeHtml = require('escape-html')

exports.hello = (req, res) => {
  const name = req.query.name || req.body.name || 'World'
  res.send(`Hello ${escapeHtml(name)}!`)
}

FTS

export function hello(name: string = 'World'): string {
  return `Hello ${name}!`
}

FTS allows you to define provider-agnostic serverless functions while also giving you strong type checking and built-in documentation for free.

How is FTS different from other RPC standards?

Functional TypeScript is a standard for declaring and invoking remote functions. This type of invocation is known as an RPC or remote procedure call.

Some other notable RPC standards include SOAP, Apache Thrift, and gRPC.

So how does FTS fit into this picture?

First off, FTS is fully compatible with these other RPC standards, with a gRPC transport layer on the roadmap.

The default HTTP handler with JSON Schema validation is the simplest way of using FTS, but it's pretty straightforward to interop with other RPC standards. For example, to use FTS with gRPC, we need to convert the JSON Schemas into protocol buffers (both of which describe the types and format of data) and add a gRPC handler which calls our compiled target JS function. Of course, there are pros and cons to using HTTP vs gRPC, with HTTP being easier to use and debug and gRPC being more efficient and scalable.

The real benefit of FTS is that the remote function definitions are just standard TypeScript, without you having to worry about the complexities of gRPC, protocol buffers, or other RPC formats. You only need to understand and write TypeScript.

Couple that with the simplicity and scalability of serverless functions, and FTS starts to become really powerful, enabling any TypeScript developer to create rock solid serverless functions easier than ever before.

How is FTS related to FaaSLang?

Functional TypeScript builds off of and shares many of the same design goals as FaaSLang. The main difference is that FaaSLang's default implementation uses JavaScript + JSDoc to generate custom schemas for function definitions, whereas FTS uses TypeScript to generate JSON Schemas for function definitions.

In our opinion, the relatively mature JSON Schema specification provides a more solid and extensible base for the core schema validation layer. JSON Schema also provides interop with a large ecosystem of existing tools and languages. For example, it would be relatively simple to extend FTS beyond TypeScript to generate JSON Schemas from any language that is supported by Quicktype (Go, Objective-C, C++, etc).

FTS also exposes a standard Node.js http handler for invoking FTS functions (req, res) => { ... }. This makes it extremely easy to integrate with popular Node.js server frameworks such as express, koa, and micro. While FaaSLang could potentially be extended to support more general usage, the default implementation currently only supports a custom API gateway server... which makes me a sad panda. 🐼

How are primitive types like Date and Buffer handled?

These are both very common and useful types that are built into TypeScript and JavaScript, but they're not supported by JSON or JSON Schema.

To resolve this, FTS uses two custom JSON Schema keywords (convertTo and convertFrom) to handle encoding and decoding these types as strings. Dates are encoded as ISO utf8 strings and Buffers are encoded as base64 strings.

All of these conversions are handled transparently and efficiently by the FTS wrappers so you can just focus on writing TypeScript.

How do I use FTS with my Serverless Provider (AWS, GCP, Azure, Now, OpenWhisk, etc)?

Great question -- this answer will be updated once we have a good answer... 😁

Related


  • typescript-json-schema - Used under the hood to convert TypeScript types to JSON Schema.
  • Quicktype - Very useful utility which uses JSON Schema as a common standard for converting between different type systems.

License

MIT © Saasify

Support my OSS work by following me on twitter twitter

More Repositories

1

chatgpt-api

Node.js client for the official ChatGPT API. 🔥
TypeScript
12,733
star
2

create-react-library

CLI for creating reusable react libraries.
JavaScript
4,783
star
3

nextjs-notion-starter-kit

Deploy your own Notion-powered website in minutes with Next.js and Vercel.
TypeScript
4,211
star
4

awesome-puppeteer

A curated list of awesome puppeteer resources.
2,073
star
5

react-particle-effect-button

Bursting particle effect buttons for React 🎉
JavaScript
1,463
star
6

awesome-ffmpeg

👻 A curated list of awesome FFmpeg resources.
847
star
7

bing-chat

Node.js client for Bing's new AI-powered search. It's like ChatGPT on steroids 🔥
TypeScript
745
star
8

ffmpeg-concat

Concats a list of videos together using ffmpeg with sexy OpenGL transitions.
JavaScript
721
star
9

chatgpt-twitter-bot

Twitter bot powered by OpenAI's ChatGPT API. It's aliveeeee 🤖
TypeScript
629
star
10

chatgpt-plugin-ts

Everything you need to start building ChatGPT Plugins in JS/TS 🔥
TypeScript
546
star
11

ffmpeg-gl-transition

FFmpeg filter for applying GLSL transitions between video streams.
C
525
star
12

OpenOpenAI

Self-hosted version of OpenAI’s new stateful Assistants API
TypeScript
509
star
13

react-static-tweets

Extremely fast static renderer for tweets.
TypeScript
506
star
14

yt-semantic-search

OpenAI-powered semantic search for any YouTube playlist – featuring the All-In Podcast. 💪
TypeScript
423
star
15

twitter-search

Instantly search across your entire Twitter history with a beautiful UI powered by Algolia.
TypeScript
347
star
16

check-links

Robustly checks an array of URLs for liveness. Extremely fast ⚡
JavaScript
324
star
17

react-modern-library-boilerplate

Boilerplate for publishing modern React modules with Rollup
JavaScript
324
star
18

puppeteer-lottie

Renders Lottie animations via Puppeteer to image, GIF, or MP4.
JavaScript
309
star
19

snapchat

NodeJS client for the unofficial Snapchat API
JavaScript
265
star
20

lqip-modern

Modern approach to Low Quality Image Placeholders (LQIP) using webp and sharp.
JavaScript
221
star
21

sms-number-verifier

Allows you to spoof SMS number verification.
JavaScript
173
star
22

puppeteer-email

Email automation driven by headless chrome.
JavaScript
149
star
23

ffmpeg-generate-video-preview

Generates an attractive image strip or GIF preview from a video.
JavaScript
138
star
24

random

The most random module on npm
TypeScript
128
star
25

scikit-learn-ts

Powerful machine learning library for Node.js – uses Python's scikit-learn under the hood.
TypeScript
125
star
26

react-background-slideshow

Sexy tiled background slideshow for React 🔥
JavaScript
111
star
27

captcha-solver

Library and CLI for automating captcha verification across multiple providers.
JavaScript
107
star
28

chatgpt-well-known-plugin-finder

Checks Alexa's top 1M websites for the presence of OpenAI's new .well-known/ai-plugin.json files
TypeScript
106
star
29

puppeteer-lottie-cli

CLI for rendering Lottie animations via Puppeteer to image, GIF, or MP4.
JavaScript
106
star
30

react-suspense-polyfill

Polyfill for the React Suspense API 😮
JavaScript
100
star
31

puppeteer-instagram

Instagram automation driven by headless chrome.
JavaScript
100
star
32

chatgpt-hackers

Join thousands of other developers, researchers, and AI enthusiasts who are building at the cutting edge of AI ✨
TypeScript
97
star
33

react-starfield-animation

✨ Canvas-based starfield animation for React.
JavaScript
96
star
34

react-mp3-recorder

Microphone recorder for React that captures mp3 audio 🎵
JavaScript
84
star
35

react-particle-animation

✨Canvas-based particle animation for React.
JavaScript
81
star
36

react-fluid-gallery

Fluid media gallery for React powered by WebGL.
JavaScript
75
star
37

primitive

Reproduce images from geometric primitives.
JavaScript
74
star
38

npm-es-modules

Breakdown of 7 different ways to use ES modules with npm today.
JavaScript
69
star
39

react-fluid-animation

Fluid media animation for React powered by WebGL.
JavaScript
68
star
40

react-before-after-slider

A sexy image comparison slider for React.
JavaScript
62
star
41

ffmpeg-extract-frames

Extracts frames from a video using ffmpeg.
JavaScript
60
star
42

puppeteer-render-text

Robust text renderer using headless chrome.
JavaScript
59
star
43

text-summarization

Automagically generates summaries from html or text.
JavaScript
54
star
44

kwote

Create beautiful quotes that capture your attention.
TypeScript
49
star
45

next-movie

Pick your next movie using Next.js 13
TypeScript
45
star
46

bens-bites-ai-search

AI search for all the best resources in AI – powered by Ben's Bites 💯
TypeScript
45
star
47

ffmpeg-cli-flags

A comprehensive list of all ffmpeg commandline flags.
44
star
48

twitter-feed-algorithm

TypeScript code exploring what an open source version of Twitter's algorithmic feed might look like.
TypeScript
42
star
49

scrape-github-trending

Tutorial for web scraping / crawling with Node.js.
JavaScript
42
star
50

clubhouse

Clubhouse API client and social graph crawler for TypeScript.
TypeScript
41
star
51

populate-movies

Populates a high quality database of movies from TMDB, IMDB, and Rotten Tomatoes.
TypeScript
36
star
52

react-fake-tweet

React renderer for tweets.
JavaScript
33
star
53

ip-set

Efficient mutable set data structure optimized for use with IPv4 and IPv6 addresses. The primary use case is for working with potentially large IP blacklists.
JavaScript
33
star
54

cf-image-proxy

Image proxy and CDN for CF workers. Simple, extremely fast, and free.
JavaScript
31
star
55

node-compat-require

Easily allow your Node program to run in a target node version range to maximize compatibility.
JavaScript
22
star
56

avp

Audio Visual Playground, or Alien vs Predator? You decide...
TypeScript
22
star
57

p-cache

Decorator to memoize the results of async functions via lru-cache.
JavaScript
22
star
58

parse-otp-message

Parses OTP messages for a verification code and service provider.
JavaScript
21
star
59

spotify-to-twitter

Example of how to create your own automated Twitter account that tweets tracks from a Spotify playlist.
JavaScript
21
star
60

gif-extract-frames

Extracts frames from a GIF including inter-frame coalescing.
JavaScript
21
star
61

puppeteer-instaquote

Use Puppeteer to create snazzy Instagram-like quote images and memes
JavaScript
20
star
62

async-await-parallel

Node.js module with simple concurrency control for awaiting an array of async results
JavaScript
20
star
63

internet-diet

Chrome extension to remove unhealthy foods from the web.
HTML
18
star
64

react-block-image

React replacement for img with more control + fallback support.
JavaScript
18
star
65

react-docgen-props-table

Beautiful Props Table for React Docgen.
JavaScript
17
star
66

lexica-api

API wrapper around Lexica.art for searching Stable Diffusion images.
TypeScript
16
star
67

puppeteer-github

GitHub automation driven by headless chrome.
JavaScript
16
star
68

google-waitlist

Sign up for Google's latest AI-powered waitlist today!
TypeScript
16
star
69

ffmpeg-extract-frame

Extracts a single frame from a video.
JavaScript
15
star
70

compare-tokenizers

A test suite comparing Node.js BPE tokenizers for use with AI models.
TypeScript
15
star
71

ffmpeg-extract-audio

Extracts an audio stream from a media file.
JavaScript
14
star
72

replicate-api

Node.js wrapper around Replicate's ML API (including dreambooth + stable diffusion).
TypeScript
14
star
73

Gravity-spritekit

iOS n-body simulation visualized with metaballs. Physics and graphics provided by SpriteKit.
Swift
14
star
74

getsmscode

API client for getsmscode.com
JavaScript
13
star
75

nala

In loving memory of Nala Das Kitten; 2010 - 2023. 💕
TypeScript
13
star
76

ffmpeg-probe

Wrapper around ffprobe for getting info about media files.
JavaScript
13
star
77

apple-april-fools-2023

Fake Apple AI product launch for April Fool's Day 2023.
TypeScript
13
star
78

ffmpeg-on-progress

Utility for robustly reporting progress with fluent-ffmpeg.
JavaScript
13
star
79

dissolve-generator

Cool 2D dissolve effect generator
JavaScript
13
star
80

abstract-object-storage

Collection of useful utilities for working with Google Cloud Storage.
JavaScript
12
star
81

Milton

C++ Rendering Framework w/ MLT, bidi path tracing, etc. and OpenGL Previews (undergrad thesis project from Brown '09)
12
star
82

koa2-mongoose-crud

Koa 2 CRUD middleware for Mongoose models.
JavaScript
11
star
83

get-mp3-duration

Computes the duration of an mp3 buffer in node or browser.
JavaScript
11
star
84

github-scraper

Misc scripts for scraping GitHub.
TypeScript
9
star
85

create-vue-library

JavaScript
9
star
86

warm-social-images

Simple CLI to warm the cache of social images in all pages from a sitemap.
JavaScript
9
star
87

primitive-cli

CLI to reproduce images from geometric primitives.
JavaScript
9
star
88

puppeteer-render-text-cli

CLI for rendering text with headless chrome.
JavaScript
9
star
89

github-is-starred-cli

CLI for checking if a user has starred a particular GitHub repo.
JavaScript
9
star
90

open-source

Keeping track of my various open source projects.
8
star
91

id-shortener

Efficient id / url shortener for NodeJS backed by pluggable storage defaulting to redis.
JavaScript
8
star
92

update-markdown-jsdoc

Updates a markdown document section with jsdoc documentation.
JavaScript
7
star
93

commit-emoji

Performs a git commit with a random emoji message. 😂 🤙 🚀
JavaScript
7
star
94

github-is-starred

Checks if a user has starred a particular GitHub repo.
JavaScript
7
star
95

puppeteer-github-cli

CLI for GitHub automation driven by headless chrome.
JavaScript
7
star
96

wahlburger

Get dem burgers
JavaScript
7
star
97

phash-im

Perceptual image hashing provided by imagemagick.
JavaScript
6
star
98

phash-gif

Perceptual GIF hashing for easily finding near-duplicate GIFs.
JavaScript
6
star
99

is-acronym

Determines whether a given string is a common English acronym.
JavaScript
5
star
100

react-springy-scroll

React utility that adds a physical springiness to elements on scroll.
JavaScript
5
star