Dive into secure and efficient coding practices with our curated list of the top 10 examples showcasing 'routing-controllers' in functional components in JavaScript. Our advanced machine learning engine meticulously scans each line of code, cross-referencing millions of open source libraries to ensure your implementation is not just functional, but also robust and secure. Elevate your React applications to new heights by mastering the art of handling side effects, API calls, and asynchronous operations with confidence and precision.
import {Body, Post, JsonController, UseBefore, BadRequestError, Param, Put, Authorized} from 'routing-controllers';
import passportJwtMiddleware from '../security/passportJwtMiddleware';
import {UnitBaseController} from './UnitBaseController';
import {FreeTextUnit} from '../models/units/FreeTextUnit';
import {IFreeTextUnit} from '../../../shared/models/units/IFreeTextUnit';
@JsonController('/units/free-texts')
@UseBefore(passportJwtMiddleware)
@Authorized(['teacher', 'admin'])
export class FreeTextUnitController extends UnitBaseController {
/*
@Post('/')
addUnit(@Body() data: any) {
// discard invalid requests
this.checkPostParam(data);
return new FreeTextUnit(data.model).save()
.then((savedFreeTextUnit) => {
return this.pushToLecture(data.lectureId, savedFreeTextUnit);
});
}
*/
import {Body, Post, JsonController, UseBefore, UploadedFile, BadRequestError, Authorized} from 'routing-controllers';
import fs = require('fs');
import passportJwtMiddleware from '../security/passportJwtMiddleware';
import {VideoUnit} from '../models/units/VideoUnit';
import {UnitController} from './UnitController';
const uploadOptions = {destination: 'uploads/'};
@JsonController('/units/upload')
@UseBefore(passportJwtMiddleware)
export class UploadUnitController extends UnitController {
@Authorized(['teacher', 'admin'])
@Post('/')
addVideoUnit(@UploadedFile('file', {options: uploadOptions}) file: any, @Body() data: any) {
// discard invalid requests
if (!data.lectureId) {
throw new BadRequestError('Misssing lectureId');
}
if (!data.name) {
throw new BadRequestError('Misssing name');
}
// path for file upload units (for now video only)
if (file) {
return new VideoUnit({
name: data.name,
description: data.description,
_course: data.courseId,
const savedTask: ITaskModel = savedTasks[i];
data.model.tasks.push(savedTask._id);
}
return new TaskUnit(data.model).save();
})
.then((savedTaskUnit) => {
return this.pushToLecture(data.lectureId, savedTaskUnit);
});
}
private addTask(task: ITask) {
return new Task(task).save();
}
@Authorized(['teacher', 'admin'])
@Put('/:id')
async updateUnit(@Param('id') id: string, @Body() unit: ITaskUnit) {
if (unit.tasks) {
unit.tasks = await Promise.all(unit.tasks.map((task) => {
// update task if exists
if (task._id) {
return Task.findByIdAndUpdate(task._id, task, {'new': true});
}
return new Task(task).save();
}));
}
return TaskUnit.findByIdAndUpdate(id, unit, {'new': true})
.then((u) => u.toObject());
}
import {Body, Post, Put, Param, JsonController, UseBefore, BadRequestError, Authorized, Get} from 'routing-controllers';
import passportJwtMiddleware from '../security/passportJwtMiddleware';
import {UnitBaseController} from './UnitBaseController';
import {TaskUnit} from '../models/units/TaskUnit';
import {ITask} from '../../../shared/models/task/ITask';
import {ITaskModel, Task} from '../models/Task';
import {ITaskUnit} from '../../../shared/models/units/ITaskUnit';
@JsonController('/units/tasks')
@UseBefore(passportJwtMiddleware)
export class TaskUnitController extends UnitBaseController {
@Authorized(['teacher', 'admin'])
@Post('/')
addTaskUnit(@Body() data: any) {
// discard invalid requests
this.checkPostParam(data);
const tasks: ITask[] = data.model.tasks;
data.model.tasks = [];
return Promise.all(tasks.map(this.addTask))
.then((savedTasks) => {
for (let i = 0; i < savedTasks.length; i++) {
const savedTask: ITaskModel = savedTasks[i];
data.model.tasks.push(savedTask._id);
import { Controller, Post, Req, Res } from 'routing-controllers';
import { Request, Response } from 'express';
import { ServerConfig } from '../../config/ServerConfig';
import BatchRenderService from '../../services/BatchRenderService';
import { processBatch } from './processBatch';
@Controller()
export class RenderController {
@Post(ServerConfig.get().endpoint)
public render(@Req() req: Request, @Res() res: Response) {
console.log('req.body: ', req.body);
// TODO
// if (isClosing()) {
// Logger.info('Starting request when closing!');
// }
const serverConfig = ServerConfig.get();
const batchRenderService = new BatchRenderService(req, res, serverConfig);
return processBatch(req.body, serverConfig.plugins, batchRenderService, serverConfig.processJobsConcurrent)
.then(() => {
async function createServer(): Promise {
try {
await openConnection();
// its important to set container before any operation you do with routing-controllers,
// including importing controllers
useContainer(Container);
const app: Application = createExpressServer({
authorizationChecker: authorizationChecker,
cors: true,
routePrefix: '/api',
defaultErrorHandler: false,
middlewares: [__dirname + '/middlewares/**/*{.ts,.js}'],
controllers: [__dirname + '/controllers/**/*{.ts,.js}']
});
const port = process.env.PORT || 3500;
app.listen(port, () => {
console.log(`server started at ${port}`);
});
} catch (error) {
console.log(error);
}
import * as koaViews from 'koa-views';
import * as path from 'path';
routingUseContainer(Container);
ormUseContainer(Container);
const koa = new Koa();
koa.use(koaViews(path.join(__dirname, 'views'), {
options: {
ext: 'ejs',
},
extension: 'ejs',
}))
// use koa app, registers all controller routes and returns you koa app instance
const app = useKoaServer(koa, {
// controllers: [`${__dirname}/controllers/**/*{.js,.ts}`],
controllers: [UserController, ApiJsonController] // we specify controllers we want to use
})
// creates koa app, registers all controller routes and returns you koa app instance
// const app = createKoaServer({
// controllers: [UserController, ApiJsonController] // we specify controllers we want to use
// });
// run koa application on port 3000
// app.listen(3000);
const databaseInitializer = async () => createConnection().then(async connection => {
console.log('连接成功')
}).catch(error => console.log(error));
const bootstrap = async () => {
await databaseInitializer();
}
});
} else if (['username', 'address', 'publicKey'].indexOf(d.sortField) > -1) {
delegates.sort((a, b) => {
if (d.sortMethod === 'ASC') {
return a[d.sortField].localeCompare(b[d.sortField]);
} else {
return b[d.sortField].localeCompare(a[d.sortField]);
}
});
}
}
return { delegates: delegates.slice(d.offset, d.limit), totalCount: d.count };
}
@Get('/fee')
@ValidateSchema()
public async getFee(@SchemaValid(schema.getFee, { castNumbers: true })
@QueryParams() params: { height?: number }) {
const f = this.system.getFees(params.height);
const { delegate } = f.fees;
delete f.fees;
return { ...f, ... { fee: delegate } };
}
@Get('/forging/getForgedByAccount')
@ValidateSchema()
public async getForgedByAccount(@SchemaValid(schema.getForgedByAccount, { castNumbers: true })
// tslint:disable-next-line max-line-length
@QueryParams() params: { generatorPublicKey: publicKey, start?: number, end?: number }) {
if (typeof(params.start) !== 'undefined' || typeof(params.end) !== 'undefined') {
const msg = this.userSrv.createMsg();
user.firstName = MockJs.Random.first();
user.lastName = MockJs.Random.last();
user.cName = MockJs.Random.cname() + MockJs.Random.cfirst();
user.age = getRandom(60);
user.sex = getRandom(100) > 50 ? 0 : 1
// save
await msg.save();
let _msg = this.userSrv.createMsg()
await _msg.save()
user.message = [msg, _msg]
await user.save()
return "Success";
}
@Get("/users/:id")
async getOne(@Param("id") id: number) {
return await User.find({ relations: ["message"], where: { id: id } });
}
@Post("/users")
post(@Body() user: any) {
return "Saving user...";
}
@Put("/users/:id")
put(@Param("id") id: number, @Body() user: any) {
return "Updating a user...";
}
@Delete("/users/:id")
remove(@Param("id") id: number) {
* "id": "5a037e6a60f72236d8e7c815"
* },
* "active": true,
* "__v": 1,
* "whitelist": [],
* "enrollType": "free",
* "lectures": [],
* "students": [],
* "teachers": [],
* "id": "5a037e6b60f72236d8e7c83d",
* "hasAccessKey": false
* }
*
* @apiError NotFoundError
*/
@Get('/:id')
async getCourse(@Param('id') id: string, @CurrentUser() currentUser: IUser) {
const course = await Course.findOne({
...this.userReadConditions(currentUser),
_id: id
})
// TODO: Do not send lectures when student has no access
.populate({
path: 'lectures',
populate: {
path: 'units',
virtuals: true,
populate: {
path: 'progressData',
match: {user: {$eq: currentUser._id}}
}
}