|
| 1 | +--- |
| 2 | +id: prefixing |
| 3 | +title: Prefixing |
| 4 | +sidebar_label: Prefixing |
| 5 | +slug: /prefixing |
| 6 | +--- |
| 7 | + |
| 8 | +## Introduction |
| 9 | + |
| 10 | +As our app grows, we might want to store our objects in a more organized way. This is where the prefix comes in. |
| 11 | + |
| 12 | +The prefix is a string that is prepended to the object key. This allows us to organize our objects in a folder-like structure. |
| 13 | + |
| 14 | +For example, if we have a bucket called `my-bucket` and we want to store our objects in a folder called `my-folder`, we can do that by prepending the prefix `my-folder/` to the object key. |
| 15 | + |
| 16 | +## Usage |
| 17 | + |
| 18 | +By default, the prefix is an empty string. This means that the object key is not modified, but if you set a prefix, when you initialize the module, the prefix will be prepended to the object key. |
| 19 | + |
| 20 | +The default algorithm for prefixing will just prepend the prefix to the object key, but you can also specify a custom algorithm. |
| 21 | + |
| 22 | +**All services like the `ObjectService` will use the prefix service by default.** |
| 23 | + |
| 24 | +## Custom prefixing |
| 25 | + |
| 26 | +In order to use a custom prefixing algorithm, you need to specify the `prefixingAlgorithm` when initializing the module. |
| 27 | + |
| 28 | +```typescript |
| 29 | +class CustomPrefixService implements IPrefixAlgorithm { |
| 30 | + prefix(remote: string, prefix: string, bucket?: string): string { |
| 31 | + return `${bucket}/${prefix}${remote}`; |
| 32 | + } |
| 33 | +} |
| 34 | + |
| 35 | +S3Module.forRoot({ |
| 36 | + region: 'region', |
| 37 | + accessKeyId: '***', |
| 38 | + secretAccessKey: '***', |
| 39 | + prefix: 'test/', |
| 40 | + prefixAlgorithm: new CustomPrefixService(), |
| 41 | +}) |
| 42 | +``` |
| 43 | + |
| 44 | +you can also use injectables |
| 45 | + |
| 46 | +```typescript |
| 47 | + class CustomPrefixWithDIService implements IPrefixAlgorithm { |
| 48 | + public constructor(private readonly globalPrefix: string) {} |
| 49 | + |
| 50 | + prefix(remote: string, prefix: string, bucket?: string): string { |
| 51 | + return `${bucket}/${this.globalPrefix}${prefix}${remote}`; |
| 52 | + } |
| 53 | +} |
| 54 | + |
| 55 | +S3Module.forRootAsync({ |
| 56 | + imports: [SomeModuleThatProvidesTheGlobalPrefix], |
| 57 | + prefixAlgorithmInject: ['GLOBAL_PREFIX'], |
| 58 | + prefixAlgorithmFactory: (globalPrefix: string) => new CustomPrefixWithDIService(globalPrefix), |
| 59 | + useFactory: () => ({ |
| 60 | + region: 'region', |
| 61 | + accessKeyId: '***', |
| 62 | + secretAccessKey: '***', |
| 63 | + prefix: 'test/', |
| 64 | + }), |
| 65 | +}) |
| 66 | +``` |
0 commit comments