Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

refactor: makeBucket #1222

Merged
merged 29 commits into from
Nov 13, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
29 commits
Select commit Hold shift + click to select a range
be572b5
put
trim21 Oct 29, 2023
9127d8d
lint fix
trim21 Oct 29, 2023
1ed96cf
fix template string
trim21 Oct 29, 2023
0ee8f79
fix test
trim21 Oct 29, 2023
06059be
fix example
trim21 Oct 29, 2023
3ee5b80
fix test
trim21 Oct 29, 2023
2a981a3
refactor: `makeBucket`
trim21 Oct 31, 2023
01f78db
callbackify
trim21 Oct 31, 2023
1a9225f
fix test
trim21 Oct 31, 2023
5ac96c8
fix test
trim21 Oct 31, 2023
cc157ed
Update functional-tests.js
trim21 Oct 31, 2023
b76c0c0
Update functional-tests.js
trim21 Oct 31, 2023
2a34b84
docs
trim21 Oct 31, 2023
82cdc0e
Update README.md
trim21 Oct 31, 2023
3e9d7b0
Update API.md
trim21 Oct 31, 2023
7157f32
Update put-object-retention.js
trim21 Nov 2, 2023
23ec423
Merge branch 'master' into putObjectRetention
trim21 Nov 3, 2023
2917862
fix lint warning
trim21 Nov 3, 2023
b3037b6
Merge remote-tracking branch 'upstream/master' into putObjectRetention
trim21 Nov 4, 2023
8f3c59d
Merge branch 'master' into makeBucket
trim21 Nov 5, 2023
f3d6e2a
Update minio.d.ts
trim21 Nov 5, 2023
6b78c87
format
trim21 Nov 5, 2023
f54c86c
remove use of xml
trim21 Nov 5, 2023
9be7d32
Merge remote-tracking branch 'upstream/master' into makeBucket
trim21 Nov 6, 2023
5bf694a
less diff
trim21 Nov 6, 2023
46e325e
Merge remote-tracking branch 'upstream/master' into makeBucket
trim21 Nov 8, 2023
d14fb35
Remove redundant code in client.ts.
trim21 Nov 8, 2023
ffffded
Fix makeBucket request payload for non-default
trim21 Nov 8, 2023
0c3208d
Merge branch 'master' into makeBucket
prakashsvmx Nov 9, 2023
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
31 changes: 13 additions & 18 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -61,11 +61,11 @@ We will use the MinIO server running at [https://play.min.io](https://play.min.i
#### file-uploader.js

```js
var Minio = require('minio')
import * as Minio from 'minio'

// Instantiate the minio client with the endpoint
// and access keys as shown below.
var minioClient = new Minio.Client({
const minioClient = new Minio.Client({
endPoint: 'play.min.io',
port: 9000,
useSSL: true,
Expand All @@ -77,22 +77,17 @@ var minioClient = new Minio.Client({
var file = '/tmp/photos-europe.tar'

// Make a bucket called europetrip.
minioClient.makeBucket('europetrip', 'us-east-1', function (err) {
if (err) return console.log(err)

console.log('Bucket created successfully in "us-east-1".')

var metaData = {
'Content-Type': 'application/octet-stream',
'X-Amz-Meta-Testing': 1234,
example: 5678,
}
// Using fPutObject API upload your file to the bucket europetrip.
minioClient.fPutObject('europetrip', 'photos-europe.tar', file, metaData, function (err, etag) {
if (err) return console.log(err)
console.log('File uploaded successfully.')
})
})
await minioClient.makeBucket('europetrip', 'us-east-1')
console.log('Bucket created successfully in "us-east-1".')

var metaData = {
'Content-Type': 'application/octet-stream',
'X-Amz-Meta-Testing': 1234,
example: 5678,
}
// Using fPutObject API upload your file to the bucket europetrip.
awaitminioClient.fPutObject('europetrip', 'photos-europe.tar', file, metaData)
console.log('File uploaded successfully.')
```

#### Run file-uploader
Expand Down
19 changes: 8 additions & 11 deletions docs/API.md
Original file line number Diff line number Diff line change
Expand Up @@ -151,26 +151,23 @@ var s3Client = new Minio.Client({

<a name="makeBucket"></a>

### makeBucket(bucketName[, region, makeOpts , callback])
### async makeBucket(bucketName, [region, makeOpts]): Promise<void>

Creates a new bucket.

**Parameters**

| Param | Type | Description |
| --------------- | ---------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `bucketName` | _string_ | Name of the bucket. |
| `region` | _string_ | Region where the bucket is created. This parameter is optional. Default value is us-east-1. |
| `makeOpts` | _object_ | Options to create a bucket. e.g `{ObjectLocking:true}` (Optional) |
| `callback(err)` | _function_ | Callback function with `err` as the error argument. `err` is null if the bucket is successfully created. If no callback is passed, a `Promise` is returned. |
| Param | Type | Description |
| ------------ | -------- | ------------------------------------------------------------------------------------------- |
| `bucketName` | _string_ | Name of the bucket. |
| `region` | _string_ | Region where the bucket is created. This parameter is optional. Default value is us-east-1. |
| `makeOpts` | _object_ | Options to create a bucket. e.g `{ObjectLocking:true}` (Optional) |

**Example**

```js
minioClient.makeBucket('mybucket', 'us-east-1', function (err) {
if (err) return console.log('Error creating bucket.', err)
console.log('Bucket created successfully in "us-east-1".')
})
await minioClient.makeBucket('mybucket', 'us-east-1')
console.log('Bucket created successfully in "us-east-1".')
```

**Example 1**
Expand Down
29 changes: 7 additions & 22 deletions docs/zh_CN/API.md
Original file line number Diff line number Diff line change
Expand Up @@ -114,37 +114,22 @@ var s3Client = new Minio.Client({
## 2. 操作存储桶
<a name="makeBucket"></a>

### makeBucket(bucketName, region[, callback])
### async makeBucket(bucketName, [region, makeOpts]): Promise<void>

创建一个新的存储桶。

__参数__

| 参数| 类型 | 描述 |
|---|---|---|
|`bucketName` | _string_ | 存储桶名称。 |
| `region` | _string_ | 存储桶被创建的region(地区),默认是us-east-1(美国东一区),下面列举的是其它合法的值: |
| | |us-east-1 |
| | |us-west-1 |
| | |us-west-2 |
| | |eu-west-1 |
| | |eu-central-1|
| | |ap-southeast-1|
| | |ap-northeast-1|
| | |ap-southeast-2|
| | |sa-east-1|
| | |cn-north-1|
|`callback(err)` |_function_ | 回调函数,`err`做为错误信息参数。如果创建存储桶成功则`err`为null。如果没有传callback的话,则返回一个`Promise`对象。 |

| 参数 | 类型 | 描述 |
|--------------|----------|---------------------------------------|
| `bucketName` | _string_ | 存储桶名称。 |
| `region` | _string_ | 存储桶被创建的region(地区),默认是us-east-1(美国东一区) |
| `makeOpts` | _object_ | 额外选项,例如: `{ObjectLocking:true}` |

__示例__


```js
minioClient.makeBucket('mybucket', 'us-east-1', function(err) {
if (err) return console.log('Error creating bucket.', err)
console.log('Bucket created successfully in "us-east-1".')
})
await minioClient.makeBucket('mybucket', 'us-east-1')
```

<a name="listBuckets"></a>
Expand Down
19 changes: 7 additions & 12 deletions examples/make-bucket.js
Original file line number Diff line number Diff line change
Expand Up @@ -17,23 +17,18 @@
// Note: YOUR-ACCESSKEYID, YOUR-SECRETACCESSKEY and my-bucketname are
// dummy values, please replace them with original values.

var Minio = require('minio')
import * as Minio from 'minio'

var s3Client = new Minio.Client({
const s3Client = new Minio.Client({
endPoint: 's3.amazonaws.com',
accessKey: 'YOUR-ACCESSKEYID',
secretKey: 'YOUR-SECRETACCESSKEY',
})
// Create a bucket name my-bucketname.
s3Client.makeBucket('my-bucketname', 'us-west-1', function (e) {
if (e) {
return console.log(e)
}
console.log('Success')
})
await s3Client.makeBucket('my-bucketname', 'us-west-1')

console.log('Success')

// Create a bucket with object locking enabled.
s3Client.makeBucket('mybucket', 'us-east-1', { ObjectLocking: true }, function (err) {
if (err) return console.log('Error creating bucket with lock .', err)
console.log('Bucket created successfully in "us-east-1" and enabled object lock')
})
await s3Client.makeBucket('mybucket', 'us-east-1', { ObjectLocking: true })
console.log('Bucket created successfully in "us-east-1" and enabled object lock')
1 change: 1 addition & 0 deletions src/errors.ts
Original file line number Diff line number Diff line change
Expand Up @@ -114,6 +114,7 @@ export class InvalidXMLError extends ExtendableError {}
*/
export class S3Error extends ExtendableError {
code?: string
region?: string
}

export class IsValidBucketNameError extends ExtendableError {}
78 changes: 78 additions & 0 deletions src/internal/client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -63,6 +63,8 @@ import type { UploadedPart } from './xml-parser.ts'
import * as xmlParsers from './xml-parser.ts'
import { parseInitiateMultipart, parseObjectLegalHoldConfig } from './xml-parser.ts'

const xml = new xml2js.Builder({ renderOpts: { pretty: false }, headless: true })

// will be replaced by bundler.
const Package = { version: process.env.MINIO_JS_PACKAGE_VERSION || 'development' }

Expand Down Expand Up @@ -113,6 +115,10 @@ export type RequestOption = Partial<IRequest> & {

export type NoResultCallback = (error: unknown) => void

export interface MakeBucketOpt {
ObjectLocking?: boolean
}

export interface RemoveOptions {
versionId?: string
governanceBypass?: boolean
Expand Down Expand Up @@ -788,6 +794,78 @@ export class TypedClient {
)
}

// Bucket operations

/**
* Creates the bucket `bucketName`.
*
*/
async makeBucket(bucketName: string, region: Region = '', makeOpts: MakeBucketOpt = {}): Promise<void> {
if (!isValidBucketName(bucketName)) {
throw new errors.InvalidBucketNameError('Invalid bucket name: ' + bucketName)
}
// Backward Compatibility
if (isObject(region)) {
makeOpts = region
region = ''
}

if (!isString(region)) {
throw new TypeError('region should be of type "string"')
}
if (!isObject(makeOpts)) {
throw new TypeError('makeOpts should be of type "object"')
}

let payload = ''

// Region already set in constructor, validate if
// caller requested bucket location is same.
if (region && this.region) {
if (region !== this.region) {
throw new errors.InvalidArgumentError(`Configured region ${this.region}, requested ${region}`)
}
}
// sending makeBucket request with XML containing 'us-east-1' fails. For
// default region server expects the request without body
if (region && region !== DEFAULT_REGION) {
payload = xml.buildObject({
CreateBucketConfiguration: {
$: { xmlns: 'http://s3.amazonaws.com/doc/2006-03-01/' },
LocationConstraint: region,
},
})
}
const method = 'PUT'
const headers: RequestHeaders = {}

if (makeOpts.ObjectLocking) {
headers['x-amz-bucket-object-lock-enabled'] = true
}

if (!region) {
region = DEFAULT_REGION
}
const finalRegion = region // type narrow
const requestOpt: RequestOption = { method, bucketName, headers }

try {
await this.makeRequestAsyncOmit(requestOpt, payload, [200], finalRegion)
} catch (err: unknown) {
if (region === '' || region === DEFAULT_REGION) {
if (err instanceof errors.S3Error) {
const errCode = err.code
const errRegion = err.region
if (errCode === 'AuthorizationHeaderMalformed' && errRegion !== '') {
// Retry with region returned as part of error
await this.makeRequestAsyncOmit(requestOpt, payload, [200], errCode)
}
}
}
throw err
}
}

async removeBucket(bucketName: string): Promise<void>

/**
Expand Down
12 changes: 1 addition & 11 deletions src/minio.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,6 @@ import type { ClientOptions, NoResultCallback, RemoveOptions } from './internal/
import { TypedClient } from './internal/client.ts'
import { CopyConditions } from './internal/copy-conditions.ts'
import { PostPolicy } from './internal/post-policy.ts'
import type { Region } from './internal/s3-endpoints.ts'
import type {
BucketItem,
BucketItemCopy,
Expand Down Expand Up @@ -52,6 +51,7 @@ import type {
export * from './helpers.ts'
export type { Region } from './internal/s3-endpoints.ts'
export { CopyConditions, PostPolicy }
export type { MakeBucketOpt } from './internal/client.ts'
export type {
BucketItem,
BucketItemCopy,
Expand Down Expand Up @@ -221,18 +221,8 @@ export class TargetConfig {
addFilterPrefix(prefix: string): void
}

export interface MakeBucketOpt {
ObjectLocking: boolean
}

// Exports from library
export class Client extends TypedClient {
// Bucket operations
makeBucket(bucketName: string, region: Region, makeOpts: MakeBucketOpt, callback: NoResultCallback): void
makeBucket(bucketName: string, region: Region, callback: NoResultCallback): void
makeBucket(bucketName: string, callback: NoResultCallback): void
makeBucket(bucketName: string, region?: Region, makeOpts?: MakeBucketOpt): Promise<void>

bucketExists(bucketName: string, callback: ResultCallback<boolean>): void
bucketExists(bucketName: string): Promise<boolean>

Expand Down
Loading
Loading