База знаний
Function's Basic – How to Write a Function With Swifty
Опубликовано Денис Завьялов on 21 November 2018 11:02

Summary 

Here’s a guide helping to code a function for swifty. Swifty supports several programming languages, so there are common things, that apply to all, and some specific.

First of all, the “function” from swifty point of view is a language, well, function called Main (capitalized, yes). The function accepts one argument called “request” which carries arguments, http method, URL sub-path and more. The function returns 2 arguments, the first one is anything that’s JSON encodable, the 2nd one is used to control the details of what should be done after the function execution.

Function 

Function has the following properties:

  • ID, that consists of name and project
  • Programming language
  • The code itself
  • Environment variables
  • Function “size”: memory limit, maximum call rate and singe call execution timeout
  • List of middleware the function has access to
  • List of S3 buckets from swifty.s3 service this function has access to
  • Auth context, that the call request is checked against before running the function

All parameters but name and code are optional.

Request 

To call a function one should define one or more triggers for the function. The basic trigger is the URL trigger that allows you to call the function using URL link. The entry point is the Main function which, when called, is given a “request” object. “Request” is the language-specific object that contains the following fields in it:

  • Args – query arguments. A set of key:value pairs. It’s accessed by language dict/map/hash object
  • Body – request body (string)
  • Method: the HTTP method that was used (get, put, delete, post, head, patch)
  • Path: URL sub-path that was used to call the function
  • Claims: JWT claims generated by auth function (if needed)

After execution a function should return two values – the first one gets JSON-encoded and is returned in the response body, the 2nd one describes details of the result. The latter one can be language-specific nil/null/none value or a key:value pairs containing status: integer HTTP code.

Triggers 

Triggers define the reason why a function can be called. There are 3 types of triggers currently:

  1. URL – the function is called via an HTTP request. The exact URL to be called is typically “https://<swifty-domain>/call/<function-ID>”. When called all query parameters are passed to function as args, method as method, the part of URL behind the ID as path and body as body
  2. Cron – periodic trigger, that runs the function. Parameters include classical crontab and key:value arguments
  3. S3 – function gets called when Swifty.S3 service generates an event on a bucket.

Few words about the URL subpath. Swifty functions get called by the URLs looking like:

https://swifty.cloud/call/{functionid}[/{subpath}]

the /call/{funcitonid} part is mandatory, while the /{subpath} may be of any length and passed as is into function.

Response 

In simple cases functions return anything JSON-encodable which gets returned by swifty to http request in body. The content type is set to 'application/json', the status code is 200 (OK).

Response object (2nd return value) can be used to change this behaviour in the future (NOTE: nothing is implemented yet). The response may be a language-specific no-value thing if no actions are needed.

Actions that are planned to be supported:

  • http status code to return
  • body content type
  • async events

Examples 

Now examples of functions just returning the “foo” argument value

== Go ==
package main
func Main(req *Request) (interface{}, *Response) {
return req.Args["foo"], nil
}
== Python ==
def Main(req):
return req.args["foo"], None
== Ruby ==
def Main(req)
return req.args["foo"], nil
== JS ==
exports.Main = function(rq) {
return { req.args.foo, null }
}
== Swift ==
func Main(rq: Request) -> (Encodable, Response?) {
return ( rq.args!["foo"], nil )
}

 

Middleware 

Middleware is a service, that Swifty platform provides for functions. Currently there are several types of middleware supported:

  1. Mongo — a mongo database;
  2. Maria — a mysql database;
  3. ObjectStorage — Amazon S3 compatible object storage;
  4. AuthJWT — special middleware that can generate and check JWTs. The name of this mware is set as auth context for functions.

Each middleware is identified by a name and project. When a middleware is attached to a function, its access credentials are passed into the function via environment variables that look like

MWARE_<TYPE><NAME>_<PARAMETER>

Each middleware type defines its own set of parameters.

Accounts 

Account represents the credentials to access any external service. It could be API key, passwords or any kind of secrets. All accounts are encrypted. An account is described by its type and associated credentials, that vary from type to type. Accounts can be “attached” to the function, which means pushing the credentials into the function code.

For example, the Generic type has the following properties:

  • Name – just a random identifier;
  • Token – this string value is encrypted and pushed into function under ACC_<TYPE><NAME>_TOKEN environment variable.

Conclusion 

Use our Quick Start Guide to try it in real life. Or learn more about swifty.library that provides some handy features to simplify functions and middleware management.

 

 

(0 голос(а))
Эта статья помогла
Эта статья не помогла

Коментарии (0)