http#request TypeScript Examples
The following examples show how to use
http#request.
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: ApiApplicationController.ts From Designer-Server with GNU General Public License v3.0 | 6 votes |
@Get("/")
@Security("jwt")
public async get(
@Request() request: exRequest,
@Query('page') page?: number,
@Query('perPage') perPage?: number
):Promise<any>{
const appRepo = getRepository(Application);
page = page || 1;
perPage = perPage || 10;
const findOptions:FindManyOptions = {
where: {
userId: request.user.id
},
take: perPage,
skip: (page - 1) * perPage
}
const apps = await appRepo.findAndCount(findOptions);
return Promise.resolve({
apps: apps[0],
page,
perPage,
totalCount: apps[1]
});
}
Example #2
Source File: ApiApplicationController.ts From Designer-Server with GNU General Public License v3.0 | 6 votes |
/**
* id를 사용하여 Appplication을 반환합니다.</br>
* Stages와 trafficConfigs를 포함합니다.
* @param applicationId
* @param request
*/
@Get("/{applicationId}")
@Security("jwt")
public async getDetail(
@Path('applicationId') applicationId: number,
@Request() request: exRequest
): Promise<Application>{
const appRepo = getRepository(Application);
const findOptions: FindOneOptions = {
relations: ["stages", "trafficConfigs"],
where: {
id: applicationId,
userId: request.user.id
}
}
const app = await appRepo.findOne(findOptions);
if(!app) { throw new ApplicationError(404, ERROR_CODE.APPLICATION.APPLICATION_NOT_FOUND) }
return Promise.resolve(app);
}
Example #3
Source File: ApiApplicationController.ts From Designer-Server with GNU General Public License v3.0 | 6 votes |
@Post("/{applicationId}/stages")
@Security("jwt")
public async postStage(
@Request() request: exRequest,
@Path('applicationId') applicationId: number
){
const appRepo = getRepository(Application);
const findOptions: FindOneOptions = {
relations: ["stages", "trafficConfigs"],
where: {
id: applicationId,
userId: request.user.id
}
}
const app = await appRepo.findOne(findOptions);
if(!app) { throw new ApplicationError(404, ERROR_CODE.APPLICATION.APPLICATION_NOT_FOUND) }
const stage = new Stage();
stage.name = stage.name = `${app.nextVersion}`;
stage.userId = request.user.id;
stage.applicationId = app.id;
await getManager().transaction(async transactionEntityManager => {
await transactionEntityManager.save(app);
await transactionEntityManager.save(stage);
});
this.setStatus(201);
return Promise.resolve(stage);
}
Example #4
Source File: ApiApplicationController.ts From Designer-Server with GNU General Public License v3.0 | 6 votes |
@Delete("/{id}")
@Security("jwt")
public async delete(
@Request() request: exRequest,
@Path("id") id: number
): Promise<any> {
const applicationRepo = getRepository(Application);
const application = await applicationRepo.findOneOrFail({
where: {
id
}
});
if(application.userId !== request.user.id) {
throw new ApplicationError(404, ERROR_CODE.APPLICATION.APPLICATION_NOT_FOUND)
}
await applicationRepo.remove(application);
return Promise.resolve();
}
Example #5
Source File: ApiApplicationController.ts From Designer-Server with GNU General Public License v3.0 | 6 votes |
@Get("/{id}/traffic-configs")
@Security("jwt")
public async getTrafficConfigs(
@Request() request: exRequest,
@Path("id") id: number
): Promise<TrafficConfig[]> {
const applicationRepo = getRepository(Application);
const application = await applicationRepo.findOne({
relations: ["trafficConfigs"],
where: {
id: id,
userId: request.user.id
}
})
const configs = application.trafficConfigs;
return Promise.resolve(configs);
}
Example #6
Source File: ApiApplicationController.ts From Designer-Server with GNU General Public License v3.0 | 6 votes |
@Post("/{id}/traffic-configs")
@Security("jwt")
public async postTrafficConfigs(
@Request() request: exRequest,
@Path("id") id: number,
@Body() trafficConfigParams: TrafficConfigParam[]
): Promise<TrafficConfig[]> {
const applicationRepo = getRepository(Application);
const trafficConfigRepo = getRepository(TrafficConfig);
const application = await applicationRepo.findOneOrFail(id)
if(application.userId !== request.user.id) {
throw Error("unAuthorized Error");
}
const trafficConfigs:TrafficConfig[] = []
for( let trafficConfigParam of trafficConfigParams) {
let newTrafficConfig = await trafficConfigRepo.findOne({
where: {
application: {
id: id
},
type: trafficConfigParam.type
}
})
if(!newTrafficConfig) newTrafficConfig = new TrafficConfig();
newTrafficConfig.application = application;
newTrafficConfig.type = trafficConfigParam.type;
newTrafficConfig.maxCount = trafficConfigParam.maxCount;
trafficConfigs.push(newTrafficConfig);
}
await trafficConfigRepo.save(trafficConfigs);
return Promise.resolve(trafficConfigs);
}
Example #7
Source File: ApiStageController.ts From Designer-Server with GNU General Public License v3.0 | 6 votes |
@Get('/')
@Security('jwt')
public async get(
@Request() request: exRequest,
@Query('page') page?: number,
@Query('perPage') perPage?: number
): Promise<Pagination<Stage>>{
const pagination = new Pagination(Stage, getConnection());
const relations = ["metas", "application"];
await pagination.findBySearchParams(relations, page, perPage, request.user.id);
return Promise.resolve(pagination);
}
Example #8
Source File: ApiStageController.ts From Designer-Server with GNU General Public License v3.0 | 6 votes |
@Get('/{stageId}')
@Security('jwt')
public async getStageById(
@Path('stageId') stageId: number,
@Request() request: exRequest
): Promise<Stage> {
const stageRepo = getRepository(Stage);
const stage = await stageRepo.findOne({
relations: ["metas", "metas.service", "application"],
where: {
id: stageId,
userId: request.user.id
}
})
if(!stage) {
throw new ApplicationError(404, ERROR_CODE.STAGE.STAGE_NOT_FOUND);
}
return stage;
}
Example #9
Source File: ApiStageController.ts From Designer-Server with GNU General Public License v3.0 | 6 votes |
/**
* 해당 API의 Swagger 문서를 불러옵니다.
* @param stageId
* @param request
*/
@Get('/{stageId}/api-docs')
// @Security('jwt')
public async getStageSwagger(
@Path('stageId') stageId: number,
@Request() request: exRequest
): Promise<any> {
const stageRepo = getRepository(Stage);
const stage = await stageRepo.findOne({
relations: ["metas", "metas.service", "application", "metas.columns", "metas.columns.params"],
where: {
id: stageId
}
})
if(!stage) {
throw new ApplicationError(404, ERROR_CODE.STAGE.STAGE_NOT_FOUND);
}
const doc = SwaggerBuilder.buildApplicationDoc(stage);
return doc;
}
Example #10
Source File: ApiStageController.ts From Designer-Server with GNU General Public License v3.0 | 6 votes |
@Post('/{id}/deploy')
@Security('jwt')
public async deploy(
@Request() request: exRequest,
@Path('id') id: number
): Promise<Stage> {
const stageRepo = getRepository(Stage);
const stage = await stageRepo.findOne({
relations:['application', 'application.trafficConfigs', 'metas', 'metas.service'],
where: {
id: id,
userId: request.user.id
}
})
if(!stage) { throw new ApplicationError(404, ERROR_CODE.STAGE.STAGE_NOT_FOUND); }
if(stage.status !== StageStatus.LOADED) { throw new ApplicationError(400, ERROR_CODE.STAGE.STAGE_NOT_LOADED); }
stage.status = StageStatus.DEPLOYED;
const queryRunner = getConnection().createQueryRunner();
await queryRunner.startTransaction();
try {
await InfuserGrpcAppClient.Instance.create(stage);
await queryRunner.manager.save(stage);
} catch(err) {
await queryRunner.rollbackTransaction();
throw new ApplicationError(500, err.message);
} finally {
await queryRunner.release();
}
this.setStatus(201);
return Promise.resolve(stage);
}
Example #11
Source File: ApiStageController.ts From Designer-Server with GNU General Public License v3.0 | 6 votes |
@Post('/{id}/undeploy')
@Security('jwt')
public async undeploy(
@Request() request: exRequest,
@Path('id') id: number
): Promise<Stage> {
const stageRepo = getRepository(Stage);
const stage = await stageRepo.findOneOrFail({
relations:['application'],
where: {
id: id,
userId: request.user.id
}
})
if(!stage) { throw new ApplicationError(404, ERROR_CODE.STAGE.STAGE_NOT_FOUND); }
if(stage.status !== StageStatus.DEPLOYED) { throw new ApplicationError(400, ERROR_CODE.STAGE.STAGE_NOT_DEPLOYED); }
stage.status = StageStatus.LOADED;
const queryRunner = getConnection().createQueryRunner();
await queryRunner.startTransaction();
try {
await InfuserGrpcAppClient.Instance.destroy(stage);
await queryRunner.manager.save(stage);
} catch(err) {
await queryRunner.rollbackTransaction();
throw new ApplicationError(500, err.message);
} finally {
await queryRunner.release();
}
this.setStatus(201);
return Promise.resolve(stage);
}
Example #12
Source File: ApiStageController.ts From Designer-Server with GNU General Public License v3.0 | 6 votes |
@Delete('/{id}')
@Security('jwt')
public async delete(
@Request() request: exRequest,
@Path('id') id: number
) {
const stageRepo = getRepository(Stage);
const stage = await stageRepo.findOneOrFail({
where: {
id: id,
userId: request.user.id
}
})
if(!stage) { throw new ApplicationError(404, ERROR_CODE.STAGE.STAGE_NOT_FOUND); }
if(stage.status === StageStatus.DEPLOYED) { throw new ApplicationError(400, ERROR_CODE.STAGE.DEPLOYED_STAGE_CANNOT_BE_DELETED); }
await stageRepo.remove(stage);
return Promise.resolve(stage);
}
Example #13
Source File: ApiApplicationController.ts From Designer-Server with GNU General Public License v3.0 | 5 votes |
/**
* Application을 생성합니다 </br>
* Application을 생성하며 default stage(v1)를 함께 생성합니다.
* @param request
* @param applicationParams
*/
@Post("/")
@Security("jwt")
public async put(
@Request() request: exRequest,
@Body() applicationParams: ApplicationParams
): Promise<Application> {
const newApplication = new Application();
newApplication.nameSpace = applicationParams.nameSpace;
newApplication.title = applicationParams.title;
newApplication.description = applicationParams.description;
newApplication.userId = request.user.id;
const dailyMaxTrafic = new TrafficConfig();
dailyMaxTrafic.maxCount = applicationParams.dailyMaxCount;
dailyMaxTrafic.type = TrafficConfigType.DAY;
const monthlyMaxTraffic = new TrafficConfig();
monthlyMaxTraffic.maxCount = applicationParams.monthlyMaxCount;
monthlyMaxTraffic.type = TrafficConfigType.MONTH;
newApplication.trafficConfigs = [dailyMaxTrafic, monthlyMaxTraffic];
const stage = new Stage();
stage.name = `${newApplication.nextVersion}`;
stage.userId = request.user.id;
newApplication.stages = [stage];
await getManager().transaction(async transactionEntityManager => {
await transactionEntityManager.save(newApplication);
dailyMaxTrafic.applicationId = newApplication.id;
monthlyMaxTraffic.applicationId = newApplication.id;
stage.applicationId = newApplication.id;
await transactionEntityManager.save(newApplication.trafficConfigs);
await transactionEntityManager.save(newApplication.stages);
});
this.setStatus(201);
return Promise.resolve(newApplication);
}
Example #14
Source File: ApiStageController.ts From Designer-Server with GNU General Public License v3.0 | 5 votes |
@Post('/{stageId}/load-data')
@Security('jwt')
public async loadData(
@Request() request: exRequest,
@Path('stageId') stageId: number
): Promise<Stage> {
const stageRepo = getRepository(Stage);
const stage = await stageRepo.findOne({
relations: ["metas", "metas.service", "application"],
where: {
id: stageId,
userId: request.user.id
}
})
if(!stage) {
throw new ApplicationError(404, ERROR_CODE.STAGE.STAGE_NOT_FOUND);
} else if(!stage.metas.every( meta => meta.status === MetaStatus.METALOADED)) {
throw new ApplicationError(400, ERROR_CODE.STAGE.ALL_METAS_SHOULD_BE_LOADED);
} else if(!stage.metas.every( meta => meta.service !== null)) {
throw new ApplicationError(400, ERROR_CODE.STAGE.ALL_METAS_SHOULD_HAVE_SERVICE);
}
stage.status = StageStatus.SCHEDULED;
stage.metas.forEach( meta => {
meta.status = MetaStatus.DATA_LOAD_SCHEDULED;
})
const queryRunner = getConnection().createQueryRunner();
try {
await queryRunner.startTransaction();
await queryRunner.manager.save(stage);
await queryRunner.manager.save(stage.metas);
BullManager.Instance.setDataLoaderSchedule(stage);
await queryRunner.commitTransaction();
} catch (err) {
await queryRunner.rollbackTransaction();
throw new ApplicationError(500, err.message);
} finally {
await queryRunner.release();
}
this.setStatus(201);
return Promise.resolve(stage);
}
Example #15
Source File: httpromise.ts From nestjs-throttler-storage-redis with MIT License | 5 votes |
export function httPromise(
url: string,
method: HttpMethods = 'GET',
headers: Record<string, any> = {},
body?: Record<string, any>,
): Promise<{ data: any; headers: Record<string, any>; status: number }> {
return new Promise((resolve, reject) => {
const req = request(url, (res) => {
res.setEncoding('utf-8');
let data = '';
res.on('data', (chunk) => {
data += chunk;
});
res.on('end', () => {
return resolve({
data: JSON.parse(data),
headers: res.headers,
status: res.statusCode,
});
});
res.on('error', (err) => {
return reject({
data: err,
headers: res.headers,
status: res.statusCode,
});
});
});
req.method = method;
Object.keys(headers).forEach((key) => {
req.setHeader(key, headers[key]);
});
switch (method) {
case 'GET':
break;
case 'POST':
case 'PUT':
case 'PATCH':
req.setHeader('Content-Type', 'application/json');
req.setHeader('Content-Length', Buffer.byteLength(Buffer.from(JSON.stringify(body))));
req.write(Buffer.from(JSON.stringify(body)));
break;
case 'DELETE':
break;
default:
reject(new Error('Invalid HTTP method'));
break;
}
req.end();
});
}