How to use the routing-controllers.Post function in routing-controllers

To help you get started, we’ve selected a few routing-controllers examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github ChatPlug / ChatPlug / src / services / api / controllers / ConnectionsController.ts View on Github external
.getMany()
    }
    return this.context.connection.getRepository(Message)
      .createQueryBuilder('message')
      .leftJoin('message.threadConnection', 'threadConnection')
      .leftJoinAndSelect('message.attachements', 'attachements')
      .leftJoinAndSelect('message.author', 'author')
      .leftJoinAndSelect('message.service', 'service')
      .where('threadConnection.id = :id', { id })
      // .andWhere('deleted = false')
      .orderBy('message.createdAt', 'DESC')
      .take(25)
      .getMany()
  }

  @Post('/')
  async createConnection(@BodyParam('connectionName', { required: true }) connectionName : string) {
    const connection = new ThreadConnection()
    connection.connectionName = connectionName
    connection.threads = []
    await this.connectionsRepository.save(connection)
    return connection
  }

  @Post('/:id/threads')
  async createThread(
    @Param('id') connectionId : number,
    @BodyParam('avatarUrl', { required: false, parse: false }) avatarUrl: string,
    @BodyParam('title', { required: true, parse: false }) title: string,
    @BodyParam('subtitle', { required: false }) subtitle: string,
    @BodyParam('externalThreadId', { required: true }) threadId : string,
    @BodyParam('serviceId', { required: true }) instanceId : number) {
github shanmugharajk / react-point-of-sale / api / src / controllers / products / ProductTypesController.ts View on Github external
}

  @Get()
  public async getProductTypes(
    @PaginationInfo() paginationInfo: IPaginationQueryParam,
    @QueryParam('q') search?: string
  ): Promise {
    const query: IFetchPageQuery = {
      search,
      perPage: paginationInfo.perPage,
      page: paginationInfo.pageNo
    };
    return await this.crudServices.fetchPages(query);
  }

  @Post()
  public async createNewProductType(
    @Body() productType: ProductType,
    @CurrentUser() userid: string
  ): Promise {
    return await this.crudServices.create(userid, productType);
  }

  @Put('/:id')
  public async updateProductType(
    @Param('id') id: string,
    @Body() data: ProductType,
    @CurrentUser() userid: string
  ) {
    return await this.crudServices.updateById(userid, { id }, data);
  }
github geli-lms / geli / api / src / controllers / NotificationSettingsController.ts View on Github external
*     {
   *         "_id": "5ab283b342949f000857b8f9",
   *         "updatedAt": "2018-03-21T16:09:23.542Z",
   *         "createdAt": "2018-03-21T16:09:23.542Z",
   *         "user": {...},
   *         "course": {...},
   *         "notificationType": "allChanges",
   *         "emailNotification": true,
   *         "__v": 0
   *     }
   *
   * @apiError BadRequestError NotificationSettings need course and user
   * @apiError BadRequestError NotificationSettings for user: x with course: y already exist
   */
  @Authorized(['student', 'teacher', 'admin'])
  @Post('/')
  async createNotificationSettings(@Body() data: any) {
    if (!data.user || !data.course) {
      throw new BadRequestError('NotificationSettings need course and user');
    }
    const notificationSettings: INotificationSettingsModel =
      await NotificationSettings.findOne({'user': data.user, 'course': data.course});
    if (notificationSettings) {
      throw new BadRequestError('NotificationSettings for user:' + data.user + ' with course: ' + data.course + ' already exist');
    }
    const settings: INotificationSettingsModel = await new NotificationSettings({
      'user': data.user,
      'course': data.course,
      'notificationType': API_NOTIFICATION_TYPE_ALL_CHANGES,
      'emailNotification': false
    }).save();
    return settings.toObject();
github epiphone / routing-controllers-openapi / sample / 01-basic / UsersController.ts View on Github external
@Get('/')
  @OpenAPI({ summary: 'Return a list of users' })
  getAll() {
    return [
      { id: 1, name: 'First user!', hobbies: [] },
      { id: 2, name: 'Second user!', hobbies: ['fishing', 'cycling'] }
    ]
  }

  @Get('/:id')
  @OpenAPI({ summary: 'Return a single user' })
  getOne(@Param('id') id: number) {
    return { name: 'User #' + id }
  }

  @Post('/')
  @OpenAPI({ summary: 'Create a new user' })
  createUser(@Body({ validate: true }) body: CreateUserBody) {
    return { ...body, id: 3 }
  }

  @Put('/')
  createManyUsers(@Body({ type: CreateUserBody }) body: CreateUserBody[]) {
    return {}
  }
}
github ktanakaj / typeorm-example / typeorm-example / src / controllers / article-controller.ts View on Github external
*     parameters:
	 *       - in: body
	 *         name: body
	 *         description: ブログ記事
	 *         required: true
	 *         schema:
	 *           $ref: '#/definitions/ArticleParams'
	 *     responses:
	 *       200:
	 *         description: 登録成功
	 *         schema:
	 *           $ref: '#/definitions/Article'
	 *       400:
	 *         $ref: '#/responses/BadRequest'
	 */
	@Post('/')
	post(@Body({ required: true }) article: Article): Promise<article> {
		return this.articleService.insert(article);
	}

	/**
	 * @swagger
	 * /articles/{id}:
	 *   put:
	 *     tags:
	 *       - articles
	 *     summary: ブログ記事更新
	 *     description: ブログ記事を更新する。
	 *     parameters:
	 *       - $ref: '#/parameters/articleIdPathParam'
	 *       - in: body
	 *         name: body</article>
github geli-lms / geli / api / src / controllers / MediaController.ts View on Github external
@Authorized(['student', 'teacher', 'admin'])
  @Get('/file/:id')
  async getFile(@Param('id') fileId: string) {
    const file = await File.findById(fileId);
    return file.toObject();
  }

  @Authorized(['teacher', 'admin'])
  @Post('/directory')
  async createRootDirectory(@Body() directory: IDirectory) {
    const savedDirectory = await new Directory(directory).save();
    return savedDirectory.toObject();
  }
  @Authorized(['teacher', 'admin'])
  @Post('/directory/:parent')
  async createDirectory(@Param('parent') parentDirectoryId: string, @Body() directory: IDirectory) {
    const savedDirectory = await new Directory(directory).save();

    const parent = await Directory.findById(parentDirectoryId);
    parent.subDirectories.push(savedDirectory);
    await parent.save();

    return savedDirectory.toObject();
  }

  @Authorized(['teacher', 'admin'])
  @Post('/file/:parent')
  async createFile(@Param('parent') parentDirectoryId: string, @UploadedFile('file', {options: uploadOptions}) uploadedFile: any) {
    const file: IFile = new File({
      name: uploadedFile.originalname,
      physicalPath: uploadedFile.path,
github jmaicaaan / express-starter-ts / src / app / controllers / user / createUser.controller.ts View on Github external
import { OrmRepository } from 'typeorm-typedi-extensions';

import { User } from '../../../database/entities';
import { RoleRepository, UserRepository } from '../../../database/repositories';
import { BcryptService } from '../../../services';

@JsonController('/users')
export class GetUsersController {

  constructor(
    @OrmRepository() private userRepository: UserRepository,
    @OrmRepository() private roleRepository: RoleRepository,
    private bcryptService: BcryptService
  ) {}

  @Post()
  public async execute(
    @Body() user: User
  ) {
    const role = await this.roleRepository.getRoleByName(user.roles[0].name);
    if (!role) {
      throw new Error(`Cannot create user, cannot get role: ${user.roles[0].name}`);
    }
    const data = await this.userRepository.createUser({
      email: user.email,
      password: await this.bcryptService.hashString(user.password),
      roles: [role]
    });
    return data;
  }
}
github nicolaspearson / node.api.boilerplate / src / templates / controllers / TemplateController.ts View on Github external
*       403:
	 *         $ref: '#/responses/Forbidden'
	 *       404:
	 *         $ref: '#/responses/NotFound'
	 *       405:
	 *         $ref: '#/responses/MethodNotAllowed'
	 *       406:
	 *         $ref: '#/responses/NotAcceptable'
	 *       500:
	 *         $ref: '#/responses/InternalServerError'
	 *       504:
	 *         $ref: '#/responses/GatewayTimeout'
	 *       default:
	 *         $ref: '#/responses/DefaultError'
	 */
	@Post('/templates/many')
	@Authorized()
	public async saveTemplateArray(@Body() templateList: object[]) {
		const transformedList = plainToClass(Template, templateList);
		return await this.templateService.saveAll(transformedList);
	}

	/**
	 * @swagger
	 * /templates/{id}:
	 *   put:
	 *     summary: Updates a specific Template object
	 *     description: Updates a specific Template object on the database
	 *     operationId: updateTemplate
	 *     tags: [template]
	 *     consumes:
	 *       - application/json
github geli-lms / geli / api / src / controllers / LectureController.ts View on Github external
*
   * @apiSuccess {Lecture} lecture Added lecture.
   *
   * @apiSuccessExample {json} Success-Response:
   *     {
   *         "_id": "5a037e6b60f72236d8e7c857",
   *         "updatedAt": "2017-11-08T22:00:11.693Z",
   *         "createdAt": "2017-11-08T22:00:11.693Z",
   *         "name": "Introduction",
   *         "description": "something about me, us, whoever",
   *         "__v": 0,
   *         "units": []
   *     }
   */
  @Authorized(['teacher', 'admin'])
  @Post('/')
  addLecture(@Body() data: any, @Req() request: Request) {
    const lectureI: ILecture = data.lecture;
    const courseId: string = data.courseId;
    return new Lecture(lectureI).save()
      .then((lecture) => {
        return Course.findById(courseId).then(course => ({course, lecture}));
      })
      .then(({course, lecture}) => {
        course.lectures.push(lecture);
        return course.save().then(updatedCourse => ({course, lecture}));
      })
      .then(({course, lecture}) => lecture.toObject());
  }

  /**
   * @api {put} /api/lecture/:id Update lecture
github geli-lms / geli / api / src / controllers / DuplicationController.ts View on Github external
* @apiSuccess {Lecture} lecture Duplicated lecture.
   *
   * @apiSuccessExample {json} Success-Response:
   *     {
   *         "_id": "5ab1a218dab93c34f8541e25",
   *         "updatedAt": "2018-03-21T00:06:48.043Z",
   *         "createdAt": "2018-03-21T00:06:48.043Z",
   *         "name": "Lecture One",
   *         "description": "Some lecture desc",
   *         "__v": 0,
   *         "units": []
   *     }
   *
   * @apiError InternalServerError Failed to duplicate lecture
   */
  @Post('/lecture/:id')
  async duplicateLecture(@Param('id') id: string, @Body() data: any, @Req() request: Request) {
    const courseId = data.courseId;
    try {
      const lectureModel: ILectureModel = await Lecture.findById(id);
      const exportedLecture: ILecture = await lectureModel.exportJSON();
      return Lecture.schema.statics.importJSON(exportedLecture, courseId);
    } catch (err) {
      const newError = new InternalServerError('Failed to duplicate lecture');
      newError.stack += '\nCaused by: ' + err.message + '\n' + err.stack;
      throw newError;
    }
  }

  /**
   * @api {post} /api/duplicate/unit/:id Duplicate unit
   * @apiName PostDuplicateUnit