すべてのプロダクト
Search
ドキュメントセンター

:2. 関数コードの記述

最終更新日:Mar 20, 2020

関数を作成したら、新しく作成した関数を入力し、選択したプログラミング言語に従って、サンプルコードをコンソールのコードエディタに貼り付けます。

Node.js

Node.js を使用する場合は、コードエディタで関数を直接記述できます。

  1. module.exports.handler = function(event, context, callback) {
  2. var event = JSON.parse(event);
  3. var content = {
  4. path: event.path,
  5. method: event.method,
  6. headers: event.headers,
  7. queryParameters: event.queryParameters,
  8. pathParameters: event.pathParameters,
  9. body: event.body
  10. // you can deal with your own logic here.
  11. }
  12. var response = {
  13. isBase64Encoded: false,
  14. statusCode: '200',
  15. headers: {
  16. 'x-custom-header': 'header value'
  17. },
  18. body: content
  19. };
  20. callback(null, response)
  21. };

Python

Python を使用する場合は、コードエディタで関数を直接記述できます。

  1. # -*- coding: utf-8 -*-
  2. import json
  3. def handler(event, context):
  4. event = json.loads(event)
  5. content = {
  6. 'path': event['path'],
  7. 'method': event['httpMethod'],
  8. 'headers': event['headers'],
  9. 'queryParameters': event['queryParameters'],
  10. 'pathParameters': event['pathParameters'],
  11. 'body': event['body']
  12. }
  13. # you can deal with your own logic here.
  14. rep = {
  15. "isBase64Encoded": "false",
  16. "statusCode": "200",
  17. "headers": {
  18. "x-custom-header": "no"
  19. },
  20. "body": content
  21. }
  22. return json.dumps(rep)

Java

Java を使用する場合は、コードと依存関係を jar ファイルに結合し、ファイルを Function Compute にアップロードする必要があります。Function Compute の Java ランタイム環境については、「Java」をご参照ください。

Java でプログラミングする場合は、Function Compute の定義済みメソッドを使用するクラスを実装する必要があります。事前定義された 2 つのメソッドが使用できます。

(推奨) PojoRequestHandler<I, O> メソッドの使用

  1. import com.aliyun.fc.runtime.Context;
  2. import com.aliyun.fc.runtime.PojoRequestHandler;
  3. import java.util.HashMap;
  4. import java.util.Map;
  5. public class ApiTriggerDemo implements PojoRequestHandler<ApiRequest, ApiResponse> {
  6. public ApiResponse handleRequest(ApiRequest request, Context context) {
  7. // Get ApiRequest info
  8. context.getLogger().info(request.toString());
  9. String path = request.getPath();
  10. String httpMethod = request.getHttpMethod();
  11. String body = request.getBody();
  12. context.getLogger().info("path:" + path);
  13. context.getLogger().info("httpMethod:" + httpMethod);
  14. context.getLogger().info("body:" + body);
  15. // Deal with your own logic here
  16. // ApiResponse example
  17. Map headers = new HashMap();
  18. boolean isBase64Encoded = false;
  19. int statusCode = 200;
  20. String returnBody = "";
  21. return new ApiResponse(headers,isBase64Encoded,statusCode,returnBody);
  22. }
  23. }

2 つの pojo クラス、ApiRequest クラスと ApiResponse クラスは、以下の通りです。注意: pojo クラスの set()get() メソッドをすべて記述してください。

  1. import java.util.Map;
  2. public class ApiRequest {
  3. private String path;
  4. private String httpMethod;
  5. private Map headers;
  6. private Map queryParameters;
  7. private Map pathParameters;
  8. private String body;
  9. private boolean isBase64Encoded;
  10. @Override
  11. public String toString() {
  12. return "Request{" +
  13. "path='" + path + '\'' +
  14. ", httpMethod='" + httpMethod + '\'' +
  15. ", headers=" + headers +
  16. ", queryParameters=" + queryParameters +
  17. ", pathParameters=" + pathParameters +
  18. ", body='" + body + '\'' +
  19. ", isBase64Encoded=" + isBase64Encoded +
  20. '}';
  21. }
  22. public String getPath() {
  23. return path;
  24. }
  25. public void setPath(String path) {
  26. this.path = path;
  27. }
  28. public String getHttpMethod() {
  29. return httpMethod;
  30. }
  31. public void setHttpMethod(String httpMethod) {
  32. this.httpMethod = httpMethod;
  33. }
  34. public Map getHeaders() {
  35. return headers;
  36. }
  37. public void setHeaders(Map headers) {
  38. this.headers = headers;
  39. }
  40. public Map getQueryParameters() {
  41. return queryParameters;
  42. }
  43. public void setQueryParameters(Map queryParameters) {
  44. this.queryParameters = queryParameters;
  45. }
  46. public Map getPathParameters() {
  47. return pathParameters;
  48. }
  49. public void setPathParameters(Map pathParameters) {
  50. this.pathParameters = pathParameters;
  51. }
  52. public String getBody() {
  53. return body;
  54. }
  55. public void setBody(String body) {
  56. this.body = body;
  57. }
  58. public boolean getIsBase64Encoded() {
  59. return this.isBase64Encoded;
  60. }
  61. public void setIsBase64Encoded(boolean base64Encoded) {
  62. this.isBase64Encoded = base64Encoded;
  63. }
  64. }
  1. import java.util.Map;
  2. public class ApiResponse {
  3. private Map headers;
  4. private boolean isBase64Encoded;
  5. private int statusCode;
  6. private String body;
  7. public ApiResponse(Map headers, boolean isBase64Encoded, int statusCode, String body) {
  8. this.headers = headers;
  9. this.isBase64Encoded = isBase64Encoded;
  10. this.statusCode = statusCode;
  11. this.body = body;
  12. }
  13. public Map getHeaders() {
  14. return headers;
  15. }
  16. public void setHeaders(Map headers) {
  17. this.headers = headers;
  18. }
  19. public boolean getIsBase64Encoded() {
  20. return isBase64Encoded;
  21. }
  22. public void setIsBase64Encoded(boolean base64Encoded) {
  23. this.isBase64Encoded = base64Encoded;
  24. }
  25. public int getStatusCode() {
  26. return statusCode;
  27. }
  28. public void setStatusCode(int statusCode) {
  29. this.statusCode = statusCode;
  30. }
  31. public String getBody() {
  32. return body;
  33. }
  34. public void setBody(String body) {
  35. this.body = body;
  36. }
  37. }

pom.xml ファイルは次のとおりです。

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <project xmlns="http://maven.apache.org/POM/4.0.0"
  3. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  4. xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  5. <modelVersion>4.0.0</modelVersion>
  6. <groupId>apiTrigger</groupId>
  7. <artifactId>apiTrigger</artifactId>
  8. <version>1.0-SNAPSHOT</version>
  9. <build>
  10. <plugins>
  11. <plugin>
  12. <groupId>org.apache.maven.plugins</groupId>
  13. <artifactId>maven-compiler-plugin</artifactId>
  14. <configuration>
  15. <source>1.8</source>
  16. <target>1.8</target>
  17. </configuration>
  18. </plugin>
  19. </plugins>
  20. </build>
  21. <dependencies>
  22. <dependency>
  23. <groupId>com.aliyun.fc.runtime</groupId>
  24. <artifactId>fc-java-core</artifactId>
  25. <version>1.0.0</version>
  26. </dependency>
  27. </dependencies>
  28. </project>

StreamRequestHandler メソッドの使用

次の例では、 StreamRequestHandler メソッドの使用について説明します。入力 InputStream は、対応する POJO クラスに変換する必要があります。pom.xml ファイルは、PojoRequestHandler<I, O> メソッドと同じように構成されています。

  1. import com.aliyun.fc.runtime.Context;
  2. import com.aliyun.fc.runtime.StreamRequestHandler;
  3. import com.aliyun.fc.runtime.Context;
  4. import com.google.gson.Gson;
  5. import java.io.*;
  6. import java.util.Base64;
  7. import java.util.HashMap;
  8. import java.util.Map;
  9. public class ApiTriggerDemo2 implements StreamRequestHandler {
  10. public void handleRequest(InputStream inputStream, OutputStream outputStream, Context context) {
  11. try {
  12. // Convert InputStream to string
  13. BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
  14. StringBuffer stringBuffer = new StringBuffer();
  15. String string = "";
  16. while ((string = bufferedReader.readLine()) != null) {
  17. stringBuffer.append(string);
  18. }
  19. String input = stringBuffer.toString();
  20. context.getLogger().info("inputStream: " + input);
  21. Request req = new Gson().fromJson(input, Request.class);
  22. context.getLogger().info("input req: ");
  23. context.getLogger().info(req.toString());
  24. String bodyReq = req.getBody();
  25. Base64.Decoder decoder = Base64.getDecoder();
  26. context.getLogger().info("body: " + new String(decoder.decode(bodyReq)));
  27. // Deal with your own logic here
  28. // construct response
  29. Map headers = new HashMap();
  30. headers.put("x-custom-header", " ");
  31. boolean isBase64Encoded = false;
  32. int statusCode = 200;
  33. Map body = new HashMap();
  34. Response resp = new Response(headers, isBase64Encoded, statusCode, body);
  35. String respJson = new Gson().toJson(resp);
  36. context.getLogger().info("outputStream: " + respJson);
  37. outputStream.write(respJson.getBytes());
  38. } catch (IOException e) {
  39. e.printStackTrace();
  40. } finally {
  41. try {
  42. outputStream.close();
  43. inputStream.close();
  44. } catch (IOException e) {
  45. e.printStackTrace();
  46. }
  47. }
  48. }
  49. class Request {
  50. private String path;
  51. private String httpMethod;
  52. private Map headers;
  53. private Map queryParameters;
  54. private Map pathParameters;
  55. private String body;
  56. private boolean isBase64Encoded;
  57. @Override
  58. public String toString() {
  59. return "Request{" +
  60. "path='" + path + '\'' +
  61. ", httpMethod='" + httpMethod + '\'' +
  62. ", headers=" + headers +
  63. ", queryParameters=" + queryParameters +
  64. ", pathParameters=" + pathParameters +
  65. ", body='" + body + '\'' +
  66. ", isBase64Encoded=" + isBase64Encoded +
  67. '}';
  68. }
  69. public String getBody() {
  70. return body;
  71. }
  72. }
  73. // FC need to return the response to API Gateway in the following JSON format
  74. class Response {
  75. private Map headers;
  76. private boolean isBase64Encoded;
  77. private int statusCode;
  78. private Map body;
  79. public Response(Map headers, boolean isBase64Encoded, int statusCode, Map body) {
  80. this.headers = headers;
  81. this.isBase64Encoded = isBase64Encoded;
  82. this.statusCode = statusCode;
  83. this.body = body;
  84. }
  85. }
  86. }