Last active
April 20, 2023 01:22
-
-
Save justsml/d496ffec4b6a283ccecef5cf0e820068 to your computer and use it in GitHub Desktop.
Using LocalStack with AWS SDK v3 - determine options for AWS client constructors.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const DEFAULT_LOCALSTACK_EDGE_PORT = 4566; | |
/** | |
* Get options for use in AWS client constructors. | |
* | |
* Configure the `AWS_ENDPOINT` environment variable to set an endpoint. | |
* | |
* ### Example | |
* | |
* To run tests w/ LocalStack: `AWS_ENDPOINT=http://127.0.0.1:4566 jest` | |
* | |
* ```js | |
* const { DynamoDBClient } = require('@aws-sdk/client-dynamodb'); | |
* | |
* const options = getClientOptions(DynamoDBClient); | |
* const client = new DynamoDBClient({ | |
* // Add other options here | |
* ...options, | |
* }); | |
* ``` | |
* | |
* To use with LocalStack, you can use the following: | |
* | |
* ```sh | |
* export AWS_ENDPOINT=http://127.0.0.1:4566 | |
* npm start | |
* ``` | |
* | |
* ### Example package.json Commands | |
* | |
* ```json | |
* "dev": "AWS_ENDPOINT=http://127.0.0.1:4566 terraform apply -auto-approve && npm start", | |
* "test": "AWS_ENDPOINT=http://127.0.0.1:4566 jest", | |
* ``` | |
* | |
* ### Note | |
* | |
* Special detection is done for the S3 client & LocalStack. The 'special' domain `s3.localhost.localstack.cloud` should resolve to `127.0.0.1`. | |
* If you are using Minio or other S3-compatible storage, you will need to set `AWS_ENDPOINT` to the correct endpoint & port. | |
* | |
* @param {*} clientClass An AWS SDK v3 client class. | |
*/ | |
export default function getClientOptions(clientClass) { | |
const endpoint = getEndpoint(); | |
const isS3Client = | |
typeof clientClass === "object" && clientClass.name === "S3Client"; | |
if (!endpoint) return {}; | |
if (clientClass === true || isS3Client) { | |
const port = endpoint.split(":")[1] || DEFAULT_LOCALSTACK_EDGE_PORT; | |
return { | |
// If you want to use virtual host addressing of buckets, you can remove `forcePathStyle: true`. | |
forcePathStyle: true, | |
endpoint: `http://s3.localhost.localstack.cloud:${port}`, | |
}; | |
} else { | |
return { | |
endpoint: getEndpoint(), | |
}; | |
} | |
} | |
function getEndpoint() { | |
const { AWS_ENDPOINT: endpoint, LOCALSTACK_HOSTNAME: localStackHostname } = | |
process.env; | |
if (endpoint) return endpoint; | |
if (localStackHostname) return `http://${localStackHostname}:4566`; | |
return undefined; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment