Expand kv api

This commit is contained in:
2023-11-19 22:35:56 -07:00
parent 7c40650b9a
commit 5a54a9ca5b
9 changed files with 154 additions and 75 deletions

View File

@@ -6,11 +6,18 @@ import {
Body,
Param,
HttpException,
Patch,
UseInterceptors,
UploadedFile,
} from '@nestjs/common';
import { KvService } from './kv.service';
import { Request } from 'express';
import { ApiTags } from '@nestjs/swagger';
import exp from 'constants';
import { FileInterceptor } from '@nestjs/platform-express';
@Controller('kv')
@ApiTags('kv')
export class KvController {
constructor(private readonly kvService: KvService) {}
@@ -42,28 +49,32 @@ export class KvController {
): Promise<string> {
if (request.headers['x-secret-key']) {
try {
return await this.kvService.getWithSecretKey(
namespace,
key,
request.headers['x-secret-key'] as string,
);
return (
await this.kvService.getWithSecretKey(
namespace,
key,
request.headers['x-secret-key'] as string,
)
).toString();
} catch (e) {
throw new HttpException(e.message, 403);
}
}
try {
return await this.kvService.get(namespace, key);
return (await this.kvService.get(namespace, key)).toString();
} catch (e) {
throw new HttpException(e.message, 403);
}
}
@Post(':namespace/:key')
@UseInterceptors(FileInterceptor('file'))
async create(
@Param('namespace') namespace: string,
@Param('key') key: string,
@Req() request: Request,
@Body() body: object,
@Body() body: object | string,
@UploadedFile('file') file: Express.Multer.File,
) {
const secretKey =
(request.headers['x-secret-key'] as string | undefined) ?? '';
@@ -72,14 +83,42 @@ export class KvController {
return await this.kvService.set(
namespace,
key,
JSON.stringify(body),
file === undefined
? typeof body === 'object'
? Buffer.from(JSON.stringify(body))
: Buffer.from(body)
: file.buffer,
secretKey,
{ public: publicFlag },
{ public: publicFlag, mimeType: file.mimetype ?? 'text/plain' },
);
}
return 'No secret key provided within X-Secret-Key header';
}
@Post(':namespace/:key/share')
async share(
@Param('namespace') namespace: string,
@Param('key') key: string,
@Req() request: Request,
@Body() body: { expiry?: number },
) {
const secretKey =
(request.headers['x-secret-key'] as string | undefined) ?? '';
if (secretKey) {
return {
expiry: body.expiry,
namespace,
key,
url: await this.kvService.shareFile(
namespace,
key,
secretKey,
body.expiry,
),
};
}
}
@Post(':namespace')
async claimNamespace(
@Param('namespace') namespace: string,
@@ -91,4 +130,22 @@ export class KvController {
throw new HttpException(e.message, 403);
}
}
@Patch(':namespace/secretKey')
async rotateSecretKey(
@Param('namespace') namespace: string,
@Req() request: Request,
) {
if (!request.headers['x-secret-key']) {
throw new HttpException("Missing 'X-Secret-Key' header", 403);
}
try {
return await this.kvService.rotateSecretKey(
namespace,
request.headers['x-secret-key'] as string,
);
} catch (e) {
throw new HttpException(e.message, 403);
}
}
}