LoginSignup
1
3

More than 3 years have passed since last update.

AWS Amplify CLIで作ったアプリに既存のAPIを取り込みたかった話

Posted at

はじめに

Amplify CLIで作ったアプリに既存のAPIを追加したくて、やってみた話です。

APIもAmplify CLIから作りたかったのですが、フックするLambdaのランタイムがPython縛りだったので、断念しました。が、近い将来サポート言語が増えると信じていますので、いったんそれまでのツナギ案です。

要件

  • Amplifyは、Multienvでステージを分離したい(prod, dev)
  • 既存APIも、Amplifyのステージをスイッチするタイミングで、同じように切り替えたい
  • API Gatewayは、Amplify CLIで作成したCognitoで認証したい
  • ソースコードは極力シンプルにしたい

方法

authRoleにAPI Invokeのポリシーをアタッチしておく。

{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Effect": "Allow",
            "Action": [
                "mobileanalytics:PutEvents",
                "cognito-sync:*",
                "cognito-identity:*",
                "execute-api:Invoke"
            ],
            "Resource": [
                "*"
            ]
        }
    ]
}

取り込みたいAPIをaws-exports.jsライクに定義する。

// NOTE: Supported runtime is NodeJS only in Amplify API,

const awsmobile = {
  "dev": [
    {
        "name": "api-dev",
        "endpoint": "https://XXXXXXXXXX.execute-api.ap-northeast-1.amazonaws.com/prod",
        "region": "ap-northeast-1"
    }
  ],
  "prod": [
    {
        "name": "api-prod",
        "endpoint": "https://XXXXXXXXXX.execute-api.ap-northeast-1.amazonaws.com/prod",
        "region": "ap-northeast-1"
    }
  ]
};


export default awsmobile;

aws-exports.jsからenv nameを取得して、APIの定義をする。
env nameは、ホスティングバケットのサフィックスになっている。
(素直にenv_nameをaws-exports.jsに吐き出してくれればいいのに、、、)

import config from './aws-exports'

const REGEX = /.*-(\w+)/
const env = config.aws_content_delivery_bucket.match(REGEX)[1]
console.log(env)

env nameでAPIの定義を取得して、configureする。

import apiExports from './aws-apiexports'

config.aws_cloud_logic_custom = apiExports[env]
Amplify.configure(config)

さいごに

これがベストかはわかりませんが、個人的にはAmplify CLIで完結しているアプリと同じ操作感になった?気がします。

1
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
3