0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

MongoDB AtlasのGraphQLを呼び出すためのクロスドメイン制約回避: Proxy使用

0
Posted at

概要

GitHub pgesに公開した静的コンテンツからMongoDB AtlasのGraphQLを呼び出す場合、
MongoDB AtlasのBearer認証により、クロスドメイン制約を回避することができる。
ただし、Bearer認証で取得するアクセストークンは30分間隔で更新が必要である。

他の回避策として、Proxyを使用してGitHub pgesと、MongoDB Atlasを同一ドメイン
とみせることにより、クロスドメイン制約を回避させてみた。

下図の構成だと別ドメインでエラーになるので、
image.png

以下のような構成を組んでみた。Lambdaをはさんだのは、CloudFrontから直接Mongodb Atlasの接続がエラーになり、すぐ解決しそうになかったから。。

image.png

GraphQLを呼び出すLambdaを作成

fetch APIが組み込まれている node v18を使用した。Lambda作成後、CloudFrontのオリジン登録用に、Lambda関数URLを生成した。

import { APIGatewayProxyEvent, APIGatewayProxyResult } from 'aws-lambda';

export const lambdaHandler = async (event: APIGatewayProxyEvent): Promise<APIGatewayProxyResult> => {
    const bound = JSON.parse(event.body);

    const queryMsg = `query {
  		webcams(query:{status:"active",location:{
                        longitude_lt:${bound.longitude_lt},
                        longitude_gte:${bound.longitude_gte},
                        latitude_lt:${bound.latitude_lt},
                        latitude_gte:${bound.latitude_gte}}}
    	,limit:200
    	,sortBy:ID_ASC) {
			id
			title
    		location{
     		 	latitude
      			longitude
    		}
            player{
               day{
                 available
                 link
              }
           }
           image{
                current{
                    thumbnail
                }    
           }
  		}
	}`;

    try {
	    const response = await fetch('https://realm.mongodb.com/api/client/v2.0/app/webcamql-qrkjj/graphql', {
  		    method: 'POST',
  		    headers: {
			    'apikey': '<apikey>' ,
    		    'Content-Type': 'application/json'
  		    },
  		    body: JSON.stringify({
      		    query: queryMsg
  		    })
	    });
        const webcamsJson = await response.json();
        return {
            statusCode: 200,
            body: JSON.stringify(webcamsJson.data.webcams),
        };
    } catch (err) {
        console.log(err);
        return {
            statusCode: 500,
            body: JSON.stringify({
                message: 'some error happened',
            }),
        };
    }
};

CloudFront側の設定

Lambda関数URLを作成後、Github pagesとLambda関数URLをCloudFrontのCloudFrontのOriginに登録。
image.png

/nuxt3-app/は、Github pagesのパス、それ以外はLambda関数を呼び出すよにうに、CloudFrontのBehaviorsに登録。
image.png

Lambda通すと、反応が遅いしそもそもAWSだと無料にならない。

0
0
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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?