> ## Documentation Index
> Fetch the complete documentation index at: https://support.locker.io/llms.txt
> Use this file to discover all available pages before exploring further.

# Hướng dẫn sử dụng

> Hướng dẫn sử dụng Locker Secrets Manager SDK cho NodeJS

## Cài đặt access key

SDK cần được cấu hình với khóa truy cập của bạn, khóa này có sẵn trong Bảng điều khiển Locker Secrets của bạn. Khởi tạo **`secret_access_key`** thành giá trị của nó. Bạn cũng cần thiết lập giá trị **`api_base`** (mặc định là `https://api.locker.io/locker_secrets`).

```jsx theme={null}
import { Locker } from 'lockerpm'
// You should not hardcode access key credentials. Instead, load them from environment variables
const locker = new Locker({
  accessKeyId: process.env.LOCKER_ACCESS_KEY_ID,
  secretAccessKey: process.env.LOCKER_ACCESS_KEY_SECRET,
  apiBase: '<your base api url>'
})
```

Tất cả các tuỳ chọn khởi tạo được liệt kê dưới đây:

| **Key**           | **Description**                                                                                                          | **Type**                     | **Required** |
| ----------------- | ------------------------------------------------------------------------------------------------------------------------ | ---------------------------- | ------------ |
| `accessKeyId`     | Your access key id                                                                                                       | `string`                     | ✅            |
| `accessKeySecret` | Your access key secret                                                                                                   | `string`                     | ✅            |
| `apiBase`         | Your server base API URL, default value is [https://api.locker.io/locker\_secrets](https://api.locker.io/locker_secrets) | `string`                     | ❌            |
| `headers`         | Custom headers for API calls                                                                                             | `{[header: string]: string}` | ❌            |
| `unsafe`          | Set TLS to unsafe if you use a server with self-signed certificate, default value is `false`                             | `boolean`                    | ❌            |
| `logLevel`        | Refer to **Logging**, default value is `1`                                                                               | `number`                     | ❌            |

Bây giờ, bạn có thể sử dụng SDK để lấy hoặc đặt các giá trị.

***

## Get secrets

Phương pháp:

* list: list all secrets

```javascript theme={null}
list: () => Promise<Secret[]>
```

* listSync: lấy tất cả secrets, nhưng được đồng bộ hoá

```javascript theme={null}
listSync: () => Secret[]
```

* get: lấy secrets theo khóa (key) và tên môi trường (tùy chọn, mặc định là môi trường TẤT CẢ), có thể trả về giá trị mặc định nếu không tìm thấy secret nào

```javascript theme={null}
get: (key: string, env?: string, defaultValue?: string) => Promise<string | undefined>
```

* getSync: lấy 1 secret nhưng được đồng bộ hoá

```javascript theme={null}
getSync: (key: string, env?: string, defaultValue?: string) => string | undefined
```

Ví dụ:

```jsx theme={null}
// Get list secrets quickly
const secrets = await locker.list()
// or
const secrets = locker.listSync()

// Get a secret value by secret key
// Replace 'ENVIRONMENT' with null or undefined for the enviroment ALL
const secretValue1 = await locker.get('SECRET_NAME_1')
const secretValue2 = await locker.get('SECRET_NAME_2', 'ENVIRONMENT')
const secretValue3 = await locker.get('SECRET_NAME_3', 'ENVIRONMENT', 'default value')
// or
const secretValue3 = locker.getSync('SECRET_NAME_3', 'ENVIRONMENT', 'default value')
```

***

## Get a secret value

Hàm này sẽ lấy giá trị bí mật bằng một khóa. Nếu khóa không tồn tại, SDK sẽ trả về **default\_value**

```python theme={null}
secret_value = locker.get("REDIS_CONNECTION", default_value="TheDefaultValue")
print(secret_value)
```

Bạn có thể lấy giá trị secrets bằng một khóa bí mật và tên môi trường cụ thể thông qua tham số `environment_name` Nếu khóa không tồn tại, SDK sẽ trả về giá trị mặc định.

```python theme={null}
secret_value = locker.get_secret(
	"REDIS_CONNECTION", 
	environment_name="staging", 
	default_value="TheDefaultValue"
)
print(secret_value)
```

***

## Tạo mới secrets

Phương pháp:

* create: tạo một secret mới có tên, giá trị, tên môi trường (tùy chọn) và mô tả (tùy chọn). Bạn không thể tạo secrets bằng cùng một khóa trong cùng một môi trường. Trả về secret mới.

```javascript theme={null}
create: (data: { key: string; value: string; environmentName?: string; description?: string }) => Promise<Secret>
```

Ví dụ

```jsx theme={null}
// Create new secret
const secret1 = await locker.create({
  key: 'key',
  value: 'value',
	description: 'a new secret'
})

// This will throw an Error
const secret2 = await locker.create({
  key: 'key',
  value: 'value 2',
})

// Use another env, this will not throw an Error
const secret3 = await locker.create({
  key: 'key',
  value: 'value',
	environmentName: 'prod'
})

// This will throw an Error
const secret4 = await locker.create({
  key: 'key',
  value: 'value 2',
	environmentName: 'prod'
})
```

***

## Cập nhật secrets

Phương pháp:

* modify: chỉnh sửa giá trị, tên môi trường hoặc mô tả của secret. Bạn không thể thay đổi secret's key. Bạn cũng không thể thay đổi môi trường sang môi trường mới đã có secret có cùng tên. Trả về secret đã cập nhật.

```javascript theme={null}
modify: (key: string, env: string, data: { value: string; environmentName?: string; description?: string }) => Promise<Secret>
```

Ví dụ:

```jsx theme={null}
// Update the secret "key" of env "ALL"
const secret = await locker.modify('key', '', {
  value: 'value 2',
	description: 'desc'
})

// Update the secret "key" of env "prod"
const secret = await locker.modify('key', 'prod', {
  value: 'value 2',
	environmentName: 'prod'
})

// This will update the env from "prod" to "ALL"
const secret = await locker.modify('key', 'prod', {
  value: 'value 2'
})

// This will update the env from "ALL" to "prod"
const secret = await locker.modify('key', '', {
  value: 'value 2',
	environmentName: 'prod'
})
```

***

## Get environments

Phương pháp:

* listEnvironments: Liệt kê tất cả môi trường

```javascript theme={null}
listEnvironments: () => Promise<Environment[]>
```

* listEnvironmentsSync: Liệt kê tất cả môi trường nhưng được đồng bộ

```javascript theme={null}
listEnvironmentsSync: () => Environment[]
```

* getEnvironment: lấy tất cả môi trường bằng tên

```javascript theme={null}
getEnvironment: (name: string) => Promise<Environment | undefined>
```

* getEnvironmentSync: lấy một môi trường nhưng được đồng bộ

```javascript theme={null}
getEnvironmentSync: () => Environment | undefined
```

Ví dụ:

```jsx theme={null}
// List environments
const environments = await locker.listEnvironments()
// or
const environments = locker.listEnvironmentsSync()

// Get an environment object by name
const environment = await locker.getEnvironment('prod')
// or
const environment = locker.getEnvironmentSync('prod')
```

***

## Retrieve an environment

Để lấy một môi trường theo tên, sử dụng `.get_environment()`

```python theme={null}
prod_env = locker.get_environment("prod")
print(prod_env.name, prod_env.external_url)
```

***

## Tạo mới environment

Phương pháp:

* createEnvironment: tạo một môi trường mới có tên, url bên ngoài (external url) và mô tả (tùy chọn). Bạn không thể tạo môi trường có cùng tên. Trả về môi trường mới.

```javascript theme={null}
createEnvironment: (data: { name: string; externalUrl: string; description?: string }) => Promise<Environment>
```

Ví dụ:

```jsx theme={null}
// Create a new environment
const env1 = await locker.createEnvironment({
  name: 'prod',
  externalUrl: 'product.prod',
	description: 'testing'
})

// This will throw an error
const env2 = await locker.createEnvironment({
  name: 'prod',
  externalUrl: 'product.prod.example'
})
```

***

## Cập nhật environment

Phương pháp:

* modifyEnvironment: chỉnh sửa mô tả và external url của môi trường. Bạn không thể thay đổi tên của môi trường. Trả về môi trường đã cập nhật.

```javascript theme={null}
modifyEnvironment: (name: string, data: { externalUrl: string; description?: string }) => Promise<Environment>
```

Ví dụ:

```jsx theme={null}
// Update an environment by name
const env = await locker.modifyEnvironment("name", {
  externalUrl: 'new value',
})
```

***

## Error Handling

SDK của Locker Secret cung cấp một số loại lỗi. Chúng có thể phản ánh các sự kiện bên ngoài, như thông tin đăng nhập không hợp lệ, gián đoạn kết nối mạng, hoặc các vấn đề về mã lỗi, như các cuộc gọi API không hợp lệ.

Nếu một vấn đề ngay lập tức ngăn chặn một hàm tiếp tục, SDK sẽ ném ra một ngoại lệ. Đây là một thực hành tốt để bắt và xử lý các ngoại lệ. Để bắt ngoại lệ, sử dụng cú pháp `try/except` của Python. Bắt `locker.error.LockerError` hoặc các lớp con của nó để xử lý các ngoại lệ chỉ định của Locker. Mỗi lớp con đại diện cho một loại ngoại lệ khác nhau. Khi bạn bắt ngoại lệ, bạn có thể sử dụng lớp của nó để chọn một phản hồi.

Ví dụ:

```python theme={null}
from locker import Locker
from locker.error import LockerError

# Create a new secret and handle error
try:
    new_secret = locker.create(key="YOUR_KEY", value="your_key_value", environment_name="staging")
    print(new_secret.key, new_secret.value, new_secret.description, new_secret.environment_name)
except LockerError as e:
    print(e.user_message)
    print(e.http_body)
```

Trong SDK, các đối tượng lỗi thuộc về `locker.error.LockerError` và các lớp con của nó. Sử dụng tài liệu cho mỗi lớp để biết cách phản ứng.

| **Code**            | **HTTP Status** | **Name**                | **Class**                            | **Description**                                                                            |
| ------------------- | --------------- | ----------------------- | ------------------------------------ | ------------------------------------------------------------------------------------------ |
| `unauthorized`      | 401             | Authentication Error    | `locker.error.AuthenticationError`   | `access_client_id` hoặc `secret_access_key` không hợp lệ                                   |
| `permission_denied` | 403             | Permission Denied Error | `locker.error.PermissionDeniedError` | Khóa truy cập không đủ quyền                                                               |
| `rate_limit`        | 429             | Rate Limit Error        | `locker.error.RateLimitError`        | Quá nhiều requests                                                                         |
| `not_found`         | 404             | Resource Not Found      | `locker.error.ResourceNotFoundError` | Tài nguyên không tìm thấy                                                                  |
| `server_error`      | 500             | API Server Error        | `locker.error.APIServerError`        | Locker server gặp vấn đề (Hiếm khi)                                                        |
| `http_error`        | 503             | API Connect Error       | `locker.error.APIConnectionError`    | Lỗi network                                                                                |
| `cli_error`         | —               | CLI Run Error           | `locker.error.CliRunError`           | Binary thực hiện mã hóa/giải mã lỗi do dữ liệu cục bộ không hợp lệ hoặc tiến trình bị ngắt |
| `locker_error`      | —               | General Locker Error    | `locker.error.LockerError`           | Lỗi chung                                                                                  |

***

## Logging

Thư viện có thể được cấu hình để phát ra thông tin đăng nhập giúp bạn hiểu rõ hơn về những gì đang diễn ra. Có một số cấp độ `NONE (0)`, `ERROR (1)`, `DEBUG (2)`. Đặt mức độ log khi tạo phiên bản Locker để kích hoạt.

```jsx theme={null}
const locker = new Locker({
  // ...
  logLevel: 1  // default is ERROR
})
```
