@nestjs/swagger#ApiQuery TypeScript Examples
The following examples show how to use
@nestjs/swagger#ApiQuery.
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: time-series.controller.ts From aqualink-app with MIT License | 6 votes |
@ApiTimeSeriesResponse()
@ApiOperation({
summary: 'Returns specified time series data for a specified site',
})
@ApiQuery({ name: 'start', example: '2021-05-18T10:20:28.017Z' })
@ApiQuery({ name: 'end', example: '2021-05-18T10:20:28.017Z' })
@ApiQuery({
name: 'metrics',
example: [Metric.BOTTOM_TEMPERATURE, Metric.TOP_TEMPERATURE],
})
@ApiQuery({ name: 'hourly', example: false, required: false })
@Get('sites/:siteId')
findSiteData(
@Param() siteDataDto: SiteDataDto,
@Query(
'metrics',
new DefaultValuePipe(Object.values(Metric)),
ParseArrayPipe,
)
metrics: Metric[],
@Query('start', ParseDatePipe) startDate?: string,
@Query('end', ParseDatePipe) endDate?: string,
@Query('hourly', ParseBoolPipe) hourly?: boolean,
) {
return this.timeSeriesService.findSiteData(
siteDataDto,
metrics,
startDate,
endDate,
hourly,
);
}
Example #2
Source File: users.controller.ts From nestjs-starter with MIT License | 6 votes |
/**
* Get deleted users - Batch
* @example GET /users/bulk?ids=1,2,3
*/
@ApiTags('Users single operation')
@ApiOperation({
summary: 'Get Deleted Users by ids- Batch',
description: 'Get users by Ids. You will have to provide a query param of ids separated by comas example: ?ids=1,2,3',
})
@ApiOkResponse({ status: 200, description: 'Success response', type: User })
@ApiUnauthorizedResponse({ status: 401, description: 'Unauthorized' })
@ApiBadGatewayResponse({ status: 502, description: 'Something happened' })
@ApiQuery({ name: 'ids', required: false, type: 'number', example: '1,2,3', explode: false })
@Get('deleted')
async getSoftdeletedUsers() {
return await this.service.getDeletedUsers();
}
Example #3
Source File: users.controller.ts From nestjs-starter with MIT License | 6 votes |
/**
* Get users by ids - Batch
* @param ids User ID integer Array
* @example GET /users/bulk?ids=1,2,3
*/
@ApiTags('Users batch operations')
@ApiOperation({
summary: 'Get Users by ids- Batch',
description: 'Get Deleted users by Ids. You will have to provide a query param of ids separated by comas example: ?ids=1,2,3',
})
@ApiOkResponse({ status: 200, description: 'Success response', type: User })
@ApiUnauthorizedResponse({ status: 401, description: 'Unauthorized' })
@ApiBadGatewayResponse({ status: 502, description: 'Something happened' })
@ApiQuery({ name: 'ids', required: false, type: 'number', example: '1,2,3', explode: false })
@Get('bulk/deleted')
async getSoftdeletedUsersByIds(@Query('ids', new ParseArrayPipe({ items: Number, separator: ',' })) ids?: number[]) {
return await this.service.getDeletedUsers(ids);
}
Example #4
Source File: users.controller.ts From nestjs-starter with MIT License | 6 votes |
/**
* Enable users
* @param ids User ID integers ?ids=1,2,3
* @example DELETE /users/bulk/enable?ids=1,2,3
*/
@ApiTags('Users batch operations')
@ApiOperation({
summary: 'Enable users - Batch',
description: 'Enable users. You will have to provide a query param of ids separated by comas example: ?ids=1,2,3',
})
@ApiOkResponse({ status: 200, description: 'Success response' })
@ApiUnauthorizedResponse({ status: 401, description: 'Unauthorized' })
@ApiBadGatewayResponse({ status: 502, description: 'Something happened' })
@ApiQuery({ name: 'ids', required: true, type: 'string', example: '1,2,3' })
@Patch('bulk/enable')
async enableMany(@Query('ids', new ParseArrayPipe({ items: Number, separator: ',' })) ids: number[]) {
return await this.service.enableMany(ids);
}
Example #5
Source File: users.controller.ts From nestjs-starter with MIT License | 6 votes |
/**
* Disable users
* @param ids User ID integers ?ids=1,2,3
* @example DELETE /users/bulk/disable?ids=1,2,3
*/
@ApiTags('Users batch operations')
@ApiOperation({
summary: 'Disable users - Batch',
description: 'Disable users. You will have to provide a query param of ids separated by comas example: ?ids=1,2,3',
})
@ApiOkResponse({ status: 200, description: 'Success response' })
@ApiUnauthorizedResponse({ status: 401, description: 'Unauthorized' })
@ApiBadGatewayResponse({ status: 502, description: 'Something happened' })
@ApiQuery({ name: 'ids', required: true, type: 'string', example: '1,2,3' })
@Patch('bulk/disable')
async disableMany(@Query('ids', new ParseArrayPipe({ items: Number, separator: ',' })) ids: number[]) {
return await this.service.disableMany(ids);
}
Example #6
Source File: users.controller.ts From nestjs-starter with MIT License | 6 votes |
/**
* Restore softdeleted users
* @param ids User ID integers ?ids=1,2,3
* @example DELETE /users/bulk/restore?ids=1,2,3
*/
@ApiTags('Users batch operations')
@ApiOperation({
summary: 'Restore users - Batch',
description: 'Restore users. You will have to provide a query param of ids separated by comas example: ?ids=1,2,3',
})
@ApiOkResponse({ status: 200, description: 'Success response' })
@ApiUnauthorizedResponse({ status: 401, description: 'Unauthorized' })
@ApiBadGatewayResponse({ status: 502, description: 'Something happened' })
@ApiQuery({ name: 'ids', required: true, type: 'string', example: '1,2,3' })
@Patch('bulk/restore')
async restoreMany(@Query('ids', new ParseArrayPipe({ items: Number, separator: ',' })) ids: number[]) {
return await this.service.restoreMany(ids);
}
Example #7
Source File: users.controller.ts From nestjs-starter with MIT License | 6 votes |
/**
* Delete many (ATENTTION: PERMANENT DELETION)
* @param ids User ID integers ?ids=1,2,3
* @example DELETE /users?ids=1,2,3
*/
@ApiTags('Users batch operations')
@ApiOperation({
summary: 'Hard delete users - Batch',
description: '(HARD DELETION) Delete users. You will have to provide a query param of ids separated by comas example: ?ids=1,2,3',
})
@ApiOkResponse({ status: 200, description: 'Success response' })
@ApiUnauthorizedResponse({ status: 401, description: 'Unauthorized' })
@ApiBadGatewayResponse({ status: 502, description: 'Something happened' })
@ApiQuery({ name: 'ids', required: true, type: 'string', example: '1,2,3' })
@Delete('bulk/hard')
async hardDeleteMany(@Query('ids', new ParseArrayPipe({ items: Number, separator: ',' })) ids: number[]) {
return await this.service.deleteMany(ids);
}
Example #8
Source File: users.controller.ts From nestjs-starter with MIT License | 6 votes |
/**
* Softdelete users (SOFT DELETION)
* @param ids User ID integers ?ids=1,2,3
* @example DELETE /users/bulk
*/
@ApiTags('Users batch operations')
@ApiOperation({
summary: 'Softdelete users - Batch',
description: '(SOFT DELETION) Delete users. You will have to provide a query param of ids separated by comas example: ?ids=1,2,3',
})
@ApiOkResponse({ status: 200, description: 'Success response' })
@ApiUnauthorizedResponse({ status: 401, description: 'Unauthorized' })
@ApiBadGatewayResponse({ status: 502, description: 'Something happened' })
@ApiBadRequestResponse({ status: 400, description: 'You will prompt with an array with the validation issues' })
@ApiQuery({ name: 'ids', required: true, type: 'string', example: '1,2,3' })
@Delete('bulk')
async deleteMany(@Query('ids', new ParseArrayPipe({ items: Number, separator: ',' })) ids: number[]) {
return await this.service.softDeleteMany(ids);
}
Example #9
Source File: users.controller.ts From nestjs-starter with MIT License | 6 votes |
/**
* Get users by ids - Batch
* @param ids User ID integer Array
* @example GET /users/bulk?ids=1,2,3
*/
@ApiTags('Users batch operations')
@ApiOperation({
summary: 'Get Users by ids- Batch',
description: 'Get users by Ids. You will have to provide a query param of ids separated by comas example: ?ids=1,2,3',
})
@ApiOkResponse({ status: 200, description: 'Success response', type: [User] })
@ApiUnauthorizedResponse({ status: 401, description: 'Unauthorized' })
@ApiBadGatewayResponse({ status: 502, description: 'Something happened' })
@ApiQuery({ name: 'ids', required: true, type: 'string', example: '1,2,3' })
@Get('bulk')
async getByIds(@Query('ids', new ParseArrayPipe({ items: Number, separator: ',' })) ids: number[]) {
return await this.service.getByIds(ids);
}
Example #10
Source File: PostController.ts From typescript-clean-architecture with MIT License | 6 votes |
@Get()
@HttpAuth(UserRole.AUTHOR, UserRole.ADMIN, UserRole.GUEST)
@HttpCode(HttpStatus.OK)
@ApiBearerAuth()
@ApiQuery({name: 'authorId', type: 'string', required: false})
@ApiResponse({status: HttpStatus.OK, type: HttpRestApiResponsePostList})
public async getPostList(
@HttpUser() user: HttpUserPayload,
@Query() query: HttpRestApiModelGetPostListQuery
): Promise<CoreApiResponse<PostUseCaseDto[]>> {
const adapter: GetPostListAdapter = await GetPostListAdapter.new({
executorId: user.id,
ownerId: query.authorId,
status: PostStatus.PUBLISHED
});
const posts: PostUseCaseDto[] = await this.getPostListUseCase.execute(adapter);
this.setFileStorageBasePath(posts);
return CoreApiResponse.success(posts);
}
Example #11
Source File: MediaController.ts From typescript-clean-architecture with MIT License | 6 votes |
@Post()
@HttpAuth(UserRole.ADMIN, UserRole.AUTHOR)
@HttpCode(HttpStatus.OK)
@UseInterceptors(FileInterceptor('file'))
@ApiBearerAuth()
@ApiConsumes('multipart/form-data')
@ApiBody({type: HttpRestApiModelCreateMediaBody})
@ApiQuery({name: 'name', type: 'string', required: false})
@ApiQuery({name: 'type', enum: MediaType})
@ApiResponse({status: HttpStatus.OK, type: HttpRestApiResponseMedia})
public async createMedia(
@Req() request: HttpRequestWithUser,
@UploadedFile() file: MulterFile,
@Query() query: HttpRestApiModelCreateMediaQuery
): Promise<CoreApiResponse<MediaUseCaseDto>> {
const adapter: CreateMediaAdapter = await CreateMediaAdapter.new({
executorId: request.user.id,
name : query.name || parse(file.originalname).name,
type : query.type,
file : file.buffer,
});
const createdMedia: MediaUseCaseDto = await this.createMediaUseCase.execute(adapter);
this.setFileStorageBasePath([createdMedia]);
return CoreApiResponse.success(createdMedia);
}
Example #12
Source File: time-series.controller.ts From aqualink-app with MIT License | 6 votes |
@ApiTimeSeriesResponse()
@ApiOperation({
summary:
'Returns specified time series data for a specified site point of interest',
})
@ApiQuery({ name: 'start', example: '2021-05-18T10:20:28.017Z' })
@ApiQuery({ name: 'end', example: '2021-05-18T10:20:28.017Z' })
@ApiQuery({
name: 'metrics',
example: [Metric.BOTTOM_TEMPERATURE, Metric.TOP_TEMPERATURE],
})
@ApiQuery({ name: 'hourly', example: false, required: false })
@Get('sites/:siteId/site-survey-points/:surveyPointId')
findSurveyPointData(
@Param() surveyPointDataDto: SurveyPointDataDto,
@Query(
'metrics',
new DefaultValuePipe(Object.values(Metric)),
ParseArrayPipe,
)
metrics: Metric[],
@Query('start', ParseDatePipe) startDate?: string,
@Query('end', ParseDatePipe) endDate?: string,
@Query('hourly') hourly?: boolean,
) {
return this.timeSeriesService.findSurveyPointData(
surveyPointDataDto,
metrics,
startDate,
endDate,
hourly,
);
}
Example #13
Source File: sites.controller.ts From aqualink-app with MIT License | 6 votes |
@ApiNestNotFoundResponse('No site was found or found site had no spotter')
@ApiOperation({ summary: 'Returns spotter data for the specified site' })
@ApiParam({ name: 'id', example: 1 })
@ApiQuery({ name: 'startDate', example: '2021-04-18T08:45:35.780Z' })
@ApiQuery({ name: 'endDate', example: '2021-05-18T08:45:35.780Z' })
@Public()
@Get(':id/spotter_data')
getSpotterData(
@Param('id', ParseIntPipe) id: number,
@Query('startDate', ParseDatePipe) startDate?: string,
@Query('endDate', ParseDatePipe) endDate?: string,
): Promise<SpotterDataDto> {
return this.sitesService.getSpotterData(id, startDate, endDate);
}
Example #14
Source File: sites.controller.ts From aqualink-app with MIT License | 6 votes |
@ApiNestNotFoundResponse('No site was found with the specified id')
@ApiNestBadRequestResponse('Start or end is not a valid date')
@ApiOperation({ summary: 'Returns daily data for the specified site' })
@ApiParam({ name: 'id', example: 1 })
@ApiQuery({ name: 'start', example: '2021-04-18T08:45:35.780Z' })
@ApiQuery({ name: 'end', example: '2021-05-18T08:45:35.780Z' })
@Public()
@Get(':id/daily_data')
findDailyData(
@Param('id', ParseIntPipe) id: number,
@Query('start') start?: string,
@Query('end') end?: string,
) {
return this.sitesService.findDailyData(id, start, end);
}
Example #15
Source File: sensors.controller.ts From aqualink-app with MIT License | 6 votes |
@ApiTimeSeriesResponse()
@ApiNestNotFoundResponse('No data were found with the specified sensor id')
@ApiOperation({ summary: 'Get data from a specified sensor' })
@ApiParam({ name: 'id', example: 'SPOT-0000' })
@ApiQuery({ name: 'startDate', example: '2021-01-10T12:00:00Z' })
@ApiQuery({ name: 'endDate', example: '2021-05-10T12:00:00Z' })
@ApiQuery({
name: 'metrics',
example: ['bottom_temperature', 'top_temperature'],
})
@Get(':id/data')
findSensorData(
@Param('id') sensorId: string,
@Query('metrics', ParseArrayPipe) metrics: string[],
@Query('startDate', ParseDatePipe) startDate?: string,
@Query('endDate', ParseDatePipe) endDate?: string,
) {
return this.coralAtlasService.findSensorData(
sensorId,
metrics,
startDate,
endDate,
);
}
Example #16
Source File: api-nested-query.decorator.ts From amplication with Apache License 2.0 | 6 votes |
// eslint-disable-next-line @typescript-eslint/ban-types,@typescript-eslint/explicit-module-boundary-types,@typescript-eslint/naming-convention
export function ApiNestedQuery(query: Function) {
const constructor = query.prototype;
const properties = Reflect.getMetadata(
"swagger/apiModelPropertiesArray",
constructor
).map((prop: any) => prop.slice(1));
const decorators = properties
.map((property: any) => {
const { required, isArray } = Reflect.getMetadata(
"swagger/apiModelProperties",
constructor,
property
);
const propertyType = Reflect.getMetadata(
"design:type",
constructor,
property
);
const typedQuery = generateApiQueryObject(
property,
propertyType,
required,
isArray
);
return [ApiExtraModels(propertyType), ApiQuery(typedQuery)];
})
.flat();
return applyDecorators(...decorators);
}
Example #17
Source File: stats.controller.ts From barista with Apache License 2.0 | 6 votes |
// What are the top 10 critical vulnerabilities discovered across all projects scanned?
@Get('/vulnerabilities')
@ApiQuery({
name: 'filterbyuser',
required: false,
type: String,
})
@ApiResponse({ status: 200 })
async getTopVulnerabilities(@Query('filterbyuser') filterbyuser: string) {
let userFilter = '';
let usergroups = [];
if (filterbyuser) {
usergroups = filterbyuser.split(',');
userFilter = 'AND p2."userId" in (:...userId)';
}
const query = `SELECT DISTINCT ssri."path" AS "name", COUNT(*) AS value
FROM project p2, security_scan_result_item ssri, security_scan_result ssr,
(SELECT DISTINCT ON (s2."projectId" ) s2.id, s2."projectId"
FROM scan s2
ORDER BY s2."projectId", s2.completed_at DESC) scan
WHERE ssr."scanId" = scan.id
AND ssri."securityScanId" = ssr."scanId"
AND scan."projectId" = p2.id
AND p2.development_type_code = 'organization'
AND ssri."severity" IN ('CRITICAL','HIGH')
${userFilter}
GROUP BY ssri."path" ORDER BY COUNT(*) DESC LIMIT 10`;
const stats = await this.rawQuery<any>(query, { userId: usergroups });
return stats;
}
Example #18
Source File: stats.controller.ts From barista with Apache License 2.0 | 6 votes |
// How many project scans are being done each month?
@Get('/projects/scans')
@ApiQuery({
name: 'filterbyuser',
required: false,
type: String,
})
@ApiResponse({ status: 200 })
async getMonthlyScans(@Query('filterbyuser') filterbyuser: string) {
let userFilter = '';
let usergroups = [];
if (filterbyuser) {
usergroups = filterbyuser.split(',');
userFilter = 'AND p2."userId" in (:...userId)';
}
const query = `SELECT date_trunc('month', ssr.created_at::date)::date AS name, COUNT(*) AS value
FROM security_scan_result ssr, project p2
WHERE ssr.created_at > date_trunc('month', CURRENT_DATE) - INTERVAL '1 year'
AND p2.development_type_code = 'organization' ${userFilter}
GROUP BY 1 ORDER BY 1 LIMIT 12;`;
const stats = await this.rawQuery<any>(query, { userId: usergroups });
return stats;
}
Example #19
Source File: stats.controller.ts From barista with Apache License 2.0 | 6 votes |
// How many new projects are being added each month?
@Get('/projects')
@ApiQuery({
name: 'filterbyuser',
required: false,
type: String,
})
@ApiResponse({ status: 200 })
async getMonthlyProjects(@Query('filterbyuser') filterbyuser: string) {
let userFilter = '';
let usergroups = [];
if (filterbyuser) {
usergroups = filterbyuser.split(',');
userFilter = 'AND p2."userId" in (:...userId)';
}
const query = `SELECT date_trunc('month', p2.created_at::date)::date AS name, COUNT(*) AS value
FROM project p2
WHERE p2.created_at > date_trunc('month', CURRENT_DATE) - INTERVAL '1 year'
AND p2.development_type_code = 'organization' ${userFilter}
GROUP BY 1 ORDER BY 1;`;
const stats = await this.rawQuery<any>(query, { userId: usergroups });
return stats;
}
Example #20
Source File: stats.controller.ts From barista with Apache License 2.0 | 6 votes |
// What are the top 10 components in use and how many times is each used across all projects scanned?
@Get('/components/scans')
@ApiQuery({
name: 'filterbyuser',
required: false,
type: String,
})
@ApiResponse({ status: 200 })
async getTopComponentScans(@Query('filterbyuser') filterbyuser: string) {
let userFilter = '';
let usergroups = [];
if (filterbyuser) {
usergroups = filterbyuser.split(',');
userFilter = 'AND p2."userId" in (:...userId)';
}
const query = `SELECT lsri."displayIdentifier" AS name, COUNT(*) AS value
FROM license l2, license_scan_result_item lsri, license_scan_result lsr, project p3,
(SELECT DISTINCT ON (s2."projectId") s2.id, s2."projectId"
FROM scan s2, project p2
WHERE p2.id = s2."projectId" AND p2.development_type_code = 'organization' ${userFilter}
ORDER BY s2."projectId", s2.completed_at DESC) scan
WHERE scan.id = lsr."scanId" AND lsri."licenseScanId" = lsr.id AND l2.id = lsri."licenseId" AND scan."projectId" = p3.id
GROUP BY 1 ORDER BY COUNT(*) DESC, 1 LIMIT 10`;
const stats = await this.rawQuery<any>(query, { userId: usergroups });
return stats;
}
Example #21
Source File: stats.controller.ts From barista with Apache License 2.0 | 6 votes |
// What are the top 10 component licenses in use and how many components are using each license?
@Get('/components')
@ApiQuery({
name: 'filterbyuser',
required: false,
type: String,
})
@ApiResponse({ status: 200 })
async getTopComponents(@Query('filterbyuser') filterbyuser: string) {
let userFilter = '';
let usergroups = [];
if (filterbyuser) {
usergroups = filterbyuser.split(',');
userFilter = 'AND p2."userId" in (:...userId)';
}
const query = `SELECT l2.name AS "name", COUNT(*) AS "value"
FROM license l2, license_scan_result_item lsri, license_scan_result lsr,
(SELECT DISTINCT ON (s2."projectId") s2.id, s2."projectId"
FROM scan s2, project p2
WHERE p2.id = s2."projectId" AND p2.development_type_code = 'organization' ${userFilter}
ORDER BY s2."projectId", s2.completed_at DESC) scan
WHERE scan.id = lsr."scanId" AND lsri."licenseScanId" = lsr.id AND l2.id = lsri."licenseId"
GROUP BY 1 ORDER BY 2 DESC LIMIT 10`;
return await this.rawQuery<any>(query, { userId: usergroups });
}
Example #22
Source File: project.controller.ts From barista with Apache License 2.0 | 5 votes |
@Get('/projects-with-statuses')
@UseInterceptors(CrudRequestInterceptor)
@ApiResponse({ status: 200, type: Project, isArray: true })
@ApiQuery({
name: 'applyUserFilter',
required: false,
type: String, // Boolean doesn't work....always becomes a string...WTF?
})
async getProjectsWithStatus(
@ParsedRequest() req: CrudRequest,
@Query('applyUserFilter') applyUserFilter: string = 'false',
@Request() request,
): Promise<Project[]> {
const { parsed, options } = req;
let userId = null;
if (applyUserFilter === 'true') {
userId = request.user.groups;
userId.push(request.user.id);
}
const answer = await this.service.getProjectsMany(parsed, options, userId);
return answer;
}
Example #23
Source File: user.controller.ts From MyAPI with MIT License | 5 votes |
@ApiOperation({ summary: 'Get all users' })
@ApiOkResponse({ description: 'List of users', type: User, isArray: true })
@ApiInternalServerErrorResponse({ description: 'Internal Server Error' })
@ApiForbiddenResponse({ description: 'You do not have the necessary role to perform this action' })
@ApiQuery({
name: 'search',
required: false,
type: String
})
@ApiQuery({
name: 'offset',
required: false,
type: Number
})
@ApiQuery({
name: 'limit',
required: false,
type: Number
})
@UseGuards(RolesGuard)
@Roles(DefaultRole.Admin)
@Get()
@HttpCode(HttpStatus.OK)
async findAll(
@Query(
'search',
new DefaultValuePipe('')
) search: string,
@Query(
'offset',
new DefaultValuePipe(0),
ParseIntPipe
) offset: number,
@Query(
'limit',
new DefaultValuePipe(10),
ParseIntPipe
) limit: number
): Promise<Array<User>> {
const users = await this.userService.findByRoleIds(
[DefaultRole.Admin, DefaultRole.User],
search,
offset,
limit
)
return users as Array<User>
}
Example #24
Source File: resource.controller.ts From radiopanel with GNU General Public License v3.0 | 5 votes |
@Get()
@ApiOperation({ summary: 'Get image', description: 'Get a manipulated image based on path' })
@ApiQuery({ name: 'f', description: 'File format', type: 'string', enum: ['png', 'jpg', 'jpeg'] })
@ApiQuery({ name: 'w', description: 'Width in px', type: 'string' })
@ApiQuery({ name: 'h', description: 'Height in px', type: 'string' })
@ApiQuery({ name: 'path', description: 'Path to image', type: 'string' })
@ApiQuery({ name: 'fit', description: 'How the image should constrain', type: 'string', enum: ['cover', 'contain', 'fill', 'inside', 'outside'] })
public async find(@Query() params: any, @Res() response: Response): Promise<any> {
response.setHeader('Cache-Control', 'max-age: 2419200');
response.setHeader('Expires', new Date(Date.now() + 2592000000).toUTCString());
const cachePath = `${slugify(params.path.replace(/^(\/uploads\.)/, ''))}-h_${params.h}-w_${params.w}-q_${params.q}-f_${params.f}`;
const cachedImage = await this.imageCacheService.findOne(cachePath);
if (!params.f || params.f === 'png') {
response.setHeader('Content-Type', 'image/png');
} else if (params.f === 'jpg' || params.f === 'jpeg') {
response.setHeader('Content-Type', 'image/jpeg');
}
if (cachedImage) {
response.setHeader('X-Cache', 'HIT');
response.end(cachedImage.data, 'utf-8');
return response;
}
const tenant = await this.tenantService.findOne();
const StorageClient = this.storageLoader.load(tenant.settings.storageMedium || 'fs');
const client = new StorageClient(tenant.settings.storageConfig);
await client.init();
const stream = await client.get(params.path.replace(/^(\/uploads)/, '').replace(/^\//, ''));
stream.on('error', () => {
response.end();
});
try {
const resizer = sharp()
.resize({
...(params.w && { width: parseInt(params.w, 10) }),
...(params.h && { height: parseInt(params.h, 10) }),
fit: params.fit || 'cover',
});
if (!params.f || params.f === 'png') {
resizer.png();
} else if (params.f === 'jpg' || params.f === 'jpeg') {
resizer.jpeg({
...(params.q && { quality: parseInt(params.q, 10) }),
});
}
response.setHeader('X-Cache', 'MISS');
const resizeStream = stream.pipe(resizer);
const chunks = [];
resizeStream.on('error', () => {
response.end();
});
resizeStream.on('data', (chunk) => {
response.write(chunk);
chunks.push(chunk);
});
resizeStream.on('end', () => {
response.end();
const imageData = Buffer.concat(chunks);
this.imageCacheService.create(imageData, cachePath);
});
} catch {
throw new BadRequestException()
}
}
Example #25
Source File: stats.controller.ts From barista with Apache License 2.0 | 5 votes |
// What is our monthly severe vulnerability index as defined by the formula:
// total number of critical or high vulnerabilities detected in scans divided by total number of packages found in scans
@Get('/highvulnerability/index')
@ApiQuery({
name: 'filterbyuser',
required: false,
type: String,
})
@ApiResponse({ status: 200 })
async getHighVulnerabilityIndex(@Query('filterbyuser') filterbyuser: string) {
let userFilter = '';
let usergroups = [];
if (filterbyuser) {
usergroups = filterbyuser.split(',');
userFilter = 'AND p2."userId" in (:...userId)';
}
const query1 = `SELECT COUNT(*)
FROM project p2, security_scan_result_item ssri, security_scan_result ssr,
(SELECT DISTINCT ON (s2."projectId") s2.id, s2."projectId"
FROM scan s2 ORDER BY s2."projectId", s2.completed_at DESC) scan
WHERE ssr."scanId" = scan.id
AND ssri."securityScanId" = ssr."scanId"
AND scan."projectId" = p2.id
AND p2.development_type_code = 'organization'
AND ssri."severity" IN ('CRITICAL','HIGH')
${userFilter}`;
const highVulnerabilityCount = await this.rawQuery<any>(query1, { userId: usergroups });
const query2 = `SELECT COUNT(*)
FROM license l2, license_scan_result_item lsri, license_scan_result lsr, project p3,
(SELECT DISTINCT ON (s2."projectId") s2.id, s2."projectId"
FROM scan s2, project p2
WHERE p2.id = s2."projectId"
AND p2.development_type_code = 'organization'
${userFilter}
ORDER BY s2."projectId", s2.completed_at DESC) scan
WHERE scan.id = lsr."scanId" AND lsri."licenseScanId" = lsr.id AND l2.id = lsri."licenseId" AND scan."projectId" = p3.id`;
const licenseComponentCount = await this.rawQuery<any>(query2, { userId: usergroups });
if (highVulnerabilityCount.length > 0 && licenseComponentCount.length > 0 && licenseComponentCount[0].count > 0) {
const highVulnerabilityIndex = (highVulnerabilityCount[0].count / licenseComponentCount[0].count) * 100;
return highVulnerabilityIndex;
}
return -1;
}
Example #26
Source File: stats.controller.ts From barista with Apache License 2.0 | 5 votes |
// What is our monthly license compliance index as defined by the formula:
// total number of not approved licenses detected in scans (i.e. yellow or red status) divided by total number of approved licenses found in scans (i.e. green status)
@Get('/licensenoncompliance/index')
@ApiQuery({
name: 'filterbyuser',
required: false,
type: String,
})
@ApiResponse({ status: 200 })
async getLicenseComplianceIndex(@Query('filterbyuser') filterbyuser: string) {
let userFilter = '';
let usergroups = [];
if (filterbyuser) {
usergroups = filterbyuser.split(',');
userFilter = 'AND p2."userId" in (:...userId)';
}
const query1 = `SELECT COUNT(*)
FROM license l2, license_scan_result_item lsri, license_scan_result lsr,
(SELECT DISTINCT ON (s2."projectId") s2.id, s2."projectId"
FROM scan s2, project p2
WHERE p2.id = s2."projectId" AND p2.development_type_code = 'organization'
${userFilter}
ORDER BY s2."projectId", s2.completed_at DESC) scan
WHERE scan.id = lsr."scanId"
AND lsri."licenseScanId" = lsr.id AND l2.id = lsri."licenseId" AND lsri.project_scan_status_type_code <> 'green'`;
const licenseProblemCount = await this.rawQuery<any>(query1, { userId: usergroups });
const query2 = `SELECT COUNT(*)
FROM license l2, license_scan_result_item lsri, license_scan_result lsr, project p3,
(SELECT DISTINCT ON (s2."projectId") s2.id, s2."projectId"
FROM scan s2, project p2
WHERE p2.id = s2."projectId"
AND p2.development_type_code = 'organization'
${userFilter}
ORDER BY s2."projectId", s2.completed_at DESC) scan
WHERE scan.id = lsr."scanId" AND lsri."licenseScanId" = lsr.id AND l2.id = lsri."licenseId" AND scan."projectId" = p3.id`;
const licenseComponentCount = await this.rawQuery<any>(query2, { userId: usergroups });
if (licenseProblemCount.length > 0 && licenseComponentCount.length > 0 && licenseComponentCount[0].count > 0) {
const licenseComplianceIndex = (licenseProblemCount[0].count / licenseComponentCount[0].count) * 100;
return licenseComplianceIndex;
}
return -1;
}