Skip to content

Standard Function

Lellansin Huang edited this page Aug 3, 2020 · 6 revisions

create a function

first of all, just type:

f create

Then, let's select faas-standard:

Generating boerplate...
? Hello, traveller.
  Which template do you like? …

 ⊙ Boilerplate
❯ faas-standard - A serverless boilerplate for aliyun fc, tencent scf and so on
  faas-layer - A serverless runtime layer boilerplate

 ⊙ Examples
  faas-react - A serverless example with react
  faas-vue - A serverless example with vue

As we see:


image.png

Install dependencies.

npm install

Directory Structure

Here is the most simplifying structure of one function. Including standard spec file f.yml and a classic TypeScript project directory.

.
├── f.yml           # standard spec file
├── package.json    # project dependencies
├── src             # resources code dir
│   └── index.ts    # function entry, demo
└── tsconfig.json   # config for tsc

Function Code

In Midway function is forming by class:

import { Func, Inject, Provide } from '@midwayjs/decorator';
import { FaaSContext, FunctionHandler } from '@midwayjs/faas';

@Provide()						// The identity for IoC container to scan
@Func('index.handler')					// Function Handler identity
export class IndexService implements FunctionHandler {

  @Inject()
  ctx: FaaSContext;  					// Function context

  async handler() {					// Function body
    return 'hello world';				// return value
  }
}

Spec File

f.yml is 是函数的定义文件,midway faas 通过这个文件,在构建时生成不同平台所能认识的文件,示例中的文件内容如下。

service:
  name: serverless-hello-world				## Service name

provider:
  name: aws						## The provider you deploy
  
functions:						## Definition of functions
  index:						   ## first function name `index`
    handler: index.handler				   ## function entry
    events:						   ## event triggers
      - http:						     ## http trigger with GET /* support
          method: get
package:						## built artifact name
  artifact: code.zip

Function Develop

Local invoke

$ f invoke -f index

:::info invoke commond is going to invoke local function directly, -f options used to specify function name. :::

Due to we chose http trigger for this function, so our result would be wrapped by a JSON object.

--------- result start --------

{"headers":{"Content-Type":["application/json; charset=utf-8"],"content-type":"text/plain"},"statusCode":200,"body":"hello world","base64Encoded":false}

--------- result end --------

Deploy

TODO