# Basic Command

## คำสั่งพื้นฐานสำหรับการใช้งานเบื้องต้น

* [ListBucketsCommand](#1-listbucketscommand)
* [PutObjectsCommand](#2-putobjectscommand)
* [ListObjectsCommand](#3-listobjectscommand)
* [DeleteObjectCommand](#4-deleteobjectcommand)
* [CopyObjectCommand](#5-copyobjectcommand)
* [GetObjectCommand](#6-getobjectcommand)
* [getSignedUrl](#7-getsignedurl)

## Prerequisite

* ต้องมี bucket สร้างเอาไว้แล้ว ([ขั้นตอนในการสร้าง bucket](https://docs-epc.gitbook.io/ncs-documents/storage/object-storage-s3/create-an-object-storage-bucket))
* มีการสร้าง subuser และ ให้สิทการเข้าถึง bucket เอาไว้แล้ว ([ขั้นตอนการสร้าง subuser และ access key](https://docs-epc.gitbook.io/ncs-documents/~/changes/U2SVceQUXXCaek3t7CoE/object-storage/create-object-storage-sub-user))

## 1) ListBucketsCommand

### สำหรับการเรียกดูรายชื่อ Buckets ภายใน project

การเรียกใช้ ListBucketsCommand ไม่จำเป็นต้องใส่ parameter ใดๆ

```javascript
import { S3Client, ListBucketsCommand } from "@aws-sdk/client-s3";

const client = new S3Client({
    region: ncs_region,
    endpoint: ncs_endpoint,
    credentials: ncs_credentials
});

const input = { }
const command = new ListBucketsCommand(input);

try {
    const response = await client.send(command);
    console.log(response);
} catch (error) {
    console.log(error);
}
```

Result

```json
{
  '$metadata': {
    httpStatusCode: 200,
    requestId: 'tx0000000000000007f36ae-006542153a-b6569ee-NCP-BKK',
    extendedRequestId: undefined,
    cfId: undefined,
    attempts: 1,
    totalRetryDelay: 0
  },
  Buckets: [
    {
      Name: 's3-client-buckets',
      CreationDate: 2023-11-01T08:53:55.139Z
    }
  ],
  Owner: {
    DisplayName: 'DevOps-Prototype',
    ID: 'xxx'
  }
}
```

## 2) PutObjectsCommand

### สำหรับการ upload ข้อมูลเข้าไปยัง Buckets

### parameter ที่จำเป็นสำหรับการใช้งาน

* Bucket (ชื่อของ Bucket)
* Body (ข้อมูลที่ต้องการอัพโหลด)
* Key (ชื่อของไฟล์ที่อัพโหลดไปยัง Bucket)

ตัวอย่างการใช้งาน PutObjectsCommand โดยมี package fs สำหรับใช้ในการอ่านไฟล์

```javascript
import { S3Client, PutObjectCommand } from "@aws-sdk/client-s3";
import * as fs from 'fs';

const client = new S3Client({
    region: ncs_region,
    endpoint: ncs_endpoint,
    credentials: ncs_credentials
});

const ncs_bucket = 's3-client-buckets';
const source = 'path/to/file/file2upload.jpg';
const dest = 'uploadedfile.jpg';
const fileContent = fs.readFileSync(source);
const input = {
    Bucket: ncs_bucket,
    Body: fileContent,
    Key: dest
}
const command = new PutObjectCommand(input);

try {
    const response = await client.send(command);
    console.log(response);
} catch (error) {
    console.log(error);
}
```

Result

```json
{
  '$metadata': {
    httpStatusCode: 200,
    requestId: 'tx00000000000000035f84a-0065485672-b8c3f38-NCP-BKK',
    extendedRequestId: undefined,
    cfId: undefined,
    attempts: 1,
    totalRetryDelay: 0
  },
  ETag: '"16de86869221ac1c9c66b9397d9845a7"'
}
```

## 3) ListObjectsCommand

สำหรับการเรียกดูรายชื่อ Objects ภายใน Bucket

## parameter ที่จำเป็นสำหรับการใช้งาน

* Bucket (ชื่อของ Bucket ที่ต้องการเรียกดู)

```javascript
import { S3Client, ListObjectsCommand } from "@aws-sdk/client-s3";

const client = new S3Client({
    region: ncs_region,
    endpoint: ncs_endpoint,
    credentials: ncs_credentials
});

const ncs_bucket = 's3-client-buckets';
const input = {
    Bucket: ncs_bucket
}
const command = new ListObjectsCommand(input);

try {
    const response = await client.send(command);
    console.log(response);
} catch (error) {
    console.log(error);
}
```

Result

<pre class="language-javascript"><code class="lang-javascript">{
  '$metadata': {
    httpStatusCode: 200,
    requestId: 'tx000000000000000371e77-0065485938-b8c3f38-NCP-BKK',
    extendedRequestId: undefined,
    cfId: undefined,
    attempts: 1,
    totalRetryDelay: 0
<strong>  },
</strong>  Contents: [
    {
      Key: 'uploadedfile.jpg',
      LastModified: 2023-11-06T03:10:44.618Z,
      ETag: '"16de86869221ac1c9c66b9397d9845a7"',
      Size: 7156660,
      StorageClass: 'STANDARD',
      Owner: [Object]
    }
  ],
  IsTruncated: false,
  Marker: '',
  MaxKeys: 1000,
  Name: 's3-client-buckets',
  Prefix: ''
}
</code></pre>

## 4) DeleteObjectCommand

สำหรับการลบ Objects ภายใน Bucket

## parameter ที่จำเป็นสำหรับการใช้งาน

* Bucket (ชื่อของ Bucket)
* Key (ชื่อของไฟล์ที่ต้องการลบ)

```javascript
import { S3Client, DeleteObjectCommand } from "@aws-sdk/client-s3";

const client = new S3Client({
    region: ncs_region,
    endpoint: ncs_endpoint,
    credentials: ncs_credentials
});

const target = 'file2delete.dum'
const input = {
    Bucket: ncs_bucket,
    Key: target
}
const command = new DeleteObjectCommand(input);

try {
    const response = await client.send(command);
    console.log(response);
} catch (error) {
    console.log(error);
}
```

Result

```json
{
  '$metadata': {
    httpStatusCode: 204,
    requestId: 'tx000000000000000378393-0065485a1e-b8c3f0e-NCP-BKK',
    extendedRequestId: undefined,
    cfId: undefined,
    attempts: 1,
    totalRetryDelay: 0
  }
}
```

## 5) CopyObjectCommand

สำหรับการ Copy Object ไปยัง Bucket อื่น หรือ path ใหม่บน Bucket

## parameter ที่จำเป็นสำหรับการใช้งาน

* Bucket (ชื่อของ Bucket ปลายทาง)
* CopySource (ข้อมูลที้ต้องการทำซ้ำ โดยมี format คือ /{source bucket name}/{source file})
* Key (ไฟล์ปลายทางจากการทำซ้ำ)

\*\* สำหรับ Credentials ที่ใช้งานนั้น จะต้องมีสิทธิ์ read จาก Bucket ต้นทาง และ สิทธิ์ write จาก Bucket ปลายทาง

<pre class="language-javascript"><code class="lang-javascript">import { S3Client, CopyObjectCommand } from "@aws-sdk/client-s3";

const client = new S3Client({
    region: ncs_region,
    endpoint: ncs_endpoint,
    credentials: ncs_credentials,
    forcePathStyle: false
});

const ncs_bucket = 's3-client-buckets';
const source = '/s3-client-buckets/source.file'
const target = 'target.file'
const input = {
    Bucket: ncs_bucket,
    CopySource: source,
    Key: target
}

const command = new CopyObjectCommand(input);
<strong>
</strong>try {
    const response = await client.send(command);
    console.log(response);
} catch (error) {
    console.log(error);
}
</code></pre>

Result

<pre class="language-json"><code class="lang-json">{
  '$metadata': {
    httpStatusCode: 200,
    requestId: 'tx0000000000000003f747c-00654b118d-b947ae8-NCP-BKK',
    extendedRequestId: undefined,
    cfId: undefined,
    attempts: 1,
    totalRetryDelay: 0
  },
  CopyObjectResult: {
    ETag: '16de86869221ac1c9c66b9397d9845a7',
    LastModified: 2023-11-08T04:41:49.846Z
  }
<strong>}
</strong></code></pre>

## 6) GetObjectCommand

สำหรับการเรียกดูข้อมูล หรือ การ Download Object บน Buckets

## parameter ที่จำเป็นสำหรับการใช้งาน

* Bucket (ชื่อของ Bucket)
* Key (ชื่อไฟล์ที่ต้องการ)

```javascript
import { S3Client, GetObjectCommand } from "@aws-sdk/client-s3";
import * as fs from 'fs';

const client = new S3Client({
    region: ncs_region,
    endpoint: ncs_endpoint,
    credentials: ncs_credentials
});

const ncs_bucket = 's3-client-buckets';
const target_file = 'ubuntu.jpeg'
const input = { 
    Bucket: ncs_bucket,
    Key: target_file
}

const command = new GetObjectCommand(input);
try {
    const response = await client.send(command);
    const inputStream = response.Body;
    const downloadPath = 'ubuntu.jpeg';
    const outputStream = fs.createWriteStream(downloadPath);
    inputStream.pipe(outputStream);
    outputStream.on('finish', () => {
      console.log(`downloaded the file successfully`);
    });
} catch (error) {
    console.log(error);
}
```

<figure><img src="https://1352697161-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fq2BYmWTMiaonrEL8QBP2%2Fuploads%2FooEC9XmuC2cPCUNjEn4Q%2FScreenshot%202566-11-08%20at%2016.31.29.png?alt=media&#x26;token=f228a3d8-360e-427c-9cc1-4e147eaf5437" alt=""><figcaption></figcaption></figure>

## 7) getSignedUrl

การสร้าง url ให้ object สำหรับการเปิดใช้งานเฉพาะ object แบบ public ชั่วคราว

## parameter ที่จำเป็นสำหรับการใช้งาน

* Bucket (ชื่อของ Bucket)
* Key (ไฟล์ข้อมูลที่ต้องการ)
* expiresIn (ระยะเวลา(นาที)ที่ url จะสามารถใช้งานได้)

\*\*ต้องทำการ install package ที่ใช้สำหรับการสร้าง presigned url เพิ่มเติม

```bash
npm install @aws-sdk/s3-request-presigner
```

```javascript
import { S3Client, GetObjectCommand } from "@aws-sdk/client-s3";
import { getSignedUrl } from "@aws-sdk/s3-request-presigner";

const client = new S3Client({
    region: ncs_region,
    endpoint: ncs_endpoint,
    credentials: ncs_credentials
});

const ncs_bucket = 's3-client-buckets';
const file2share = 'hello-world.jpeg'
const input = { 
    Bucket: ncs_bucket,
    Key: file2share
}

const command = new GetObjectCommand(input);

try {
    const response = await getSignedUrl(client, command, { expiresIn: 3600 });
		console.log(response);
} catch (error) {
    console.log(error);
}
```

ผลลัพธ์ที่ได้ จะเป็น url สำหรับการเปิดดูข้อมูล

<https://s3-client-buckets.s3-bkk.nipa.cloud/hello-world.jpeg?X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Content-Sha256=UNSIGNED-PAYLOAD&X-Amz-Credential=X2EGTHMCW02X0KVQS1B8%2F20231109%2FNCP-TH%2Fs3%2Faws4_request&X-Amz-Date=20231109T082113Z&X-Amz-Expires=3600&X-Amz-Signature=2763b0d070d2a4f3cd561ac9cfd4fb984c132e06c87a418fad3fb4a5014c288d&X-Amz-SignedHeaders=host&x-id=GetObject>

{% hint style="info" %}
อ้างอิง

<https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/s3/>
{% endhint %}
