Skip to content

Commit

Permalink
[Feat] Get code snippet contents
Browse files Browse the repository at this point in the history
Added a service method for retrieving code snippet file contents.
Added the service method to the GET "/code-snppets" endpoint.
References #18.
  • Loading branch information
angel-penchev committed Oct 20, 2021
1 parent ce0381e commit b3d5f00
Show file tree
Hide file tree
Showing 2 changed files with 35 additions and 11 deletions.
27 changes: 17 additions & 10 deletions server/src/code-snippets/controllers/code-snippets.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -26,20 +26,27 @@ import { CodeSnippetsService } from '../services/code-snippets.service';
export class CodeSnippetsController {
constructor(private readonly codeSnippetsService: CodeSnippetsService) {}

@Get(':subdirectory(*)|/')
@Get(':path(*)')
@HttpCode(HttpStatus.OK)
@UseGuards(AuthSessionGuard)
@ApiCookieAuth()
@ApiOkResponse({ description: 'Tree of user files.' })
@ApiOkResponse({
description:
'Tree of user files in a directory or the contents of a file specified.',
})
@ApiForbiddenResponse({ description: 'No user logon.' })
async getSubdirectory(
@Req() req: Request,
@Param('subdirectory') subdirectory: string,
) {
return await this.codeSnippetsService.listUserCodeSnippets(
req.user['username'],
subdirectory ?? '',
);
async getSubdirectory(@Req() req: Request, @Param('path') path: string) {
path ??= '';

return path.endsWith('/') || path === ''
? await this.codeSnippetsService.listUserCodeSnippets(
req.user['username'],
path,
)
: await this.codeSnippetsService.getUserCodeSnippet(
req.user['username'],
path,
);
}

@Put(':filepath(*)')
Expand Down
19 changes: 18 additions & 1 deletion server/src/code-snippets/services/code-snippets.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,23 @@ export class CodeSnippetsService {
return tree;
}

async getUserCodeSnippet(username: string, filepath: string) {
const completeFilepath = `${username}/${filepath}`;

if (completeFilepath.endsWith('/')) {
throw new CodeSnippetsError(CodeSnippetsErrorCode.INVALID_FILE_PATH);
}

const queryResponse = await this.s3
.getObject({
Bucket: configObject.aws.codeSnippetsS3Bucket,
Key: completeFilepath,
})
.promise();

return queryResponse.Body.toString();
}

async saveUserCodeSnippet(username: string, filepath: string, body: string) {
const completeFilepath = `${username}/${filepath}`;

Expand All @@ -68,6 +85,6 @@ export class CodeSnippetsService {
}

// If directory => create empty object if it doesn't already exist and run again
return this.addToFileTree((tree[item.shift()] ??= {}), item);
return this.addToFileTree((tree[item.shift() + '/'] ??= {}), item);
}
}

0 comments on commit b3d5f00

Please sign in to comment.