Skip to content

Commit

Permalink
Merge pull request #23 from ThreeDify/dev
Browse files Browse the repository at this point in the history
Dev => Master
  • Loading branch information
silwalanish authored Apr 1, 2021
2 parents 3d21329 + 26ddf45 commit e43d2b6
Show file tree
Hide file tree
Showing 6 changed files with 101 additions and 63 deletions.
81 changes: 57 additions & 24 deletions src/controllers/reconstructions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ import NewReconstruction from '../domain/NewReconstruction';
import reconstructionService from '../services/reconstructions';
import ReconstructionState from '../domain/ReconstructionState';
import { AuthRequestWithImages } from '../middlewares/uploadImage';
import { AuthenticatedRequest } from '../middlewares/authenticateUser';
import ReconstructionCreationResponse from '../domain/ReconstructionCreationResponse';
import { AuthRequestWithReconstructionFile } from '../middlewares/uploadReconstruction';

Expand All @@ -23,7 +24,7 @@ export async function index(
req: Request,
res: Response<PaginatedResult<Reconstruction>>,
next: NextFunction
) {
): Promise<void> {
try {
const paginationQuery: PaginationQuery = getPaginationQuery(req.query);

Expand Down Expand Up @@ -57,10 +58,10 @@ export async function reconstruction(
req: Request,
res: Response<Reconstruction>,
next: NextFunction
) {
): Promise<void> {
try {
debug('Fetching requested reconstruction: %d', +req.params.id);
let reconstruction:
const reconstruction:
| Reconstruction
| undefined = await reconstructionService.fetchReconstructionById(
+req.params.id
Expand Down Expand Up @@ -90,10 +91,10 @@ export async function reconstructionFailed(
req: Request,
res: Response,
next: NextFunction
) {
): Promise<void> {
try {
debug('Fetching requested reconstruction: %d', +req.params.id);
let reconstruction:
const reconstruction:
| Reconstruction
| undefined = await reconstructionService.fetchReconstructionById(
+req.params.id
Expand Down Expand Up @@ -131,12 +132,12 @@ export async function reconstructionCompleted(
req: Request,
res: Response,
next: NextFunction
) {
): Promise<void> {
const authReq: AuthRequestWithReconstructionFile = req as AuthRequestWithReconstructionFile;

try {
debug('Fetching requested reconstruction: %d', +req.params.id);
let reconstruction:
const reconstruction:
| Reconstruction
| undefined = await reconstructionService.fetchReconstructionById(
+req.params.id
Expand Down Expand Up @@ -174,10 +175,10 @@ export async function reconstructionFile(
req: Request,
res: Response,
next: NextFunction
) {
): Promise<void> {
try {
debug('Fetching requested reconstruction: %d', +req.params.id);
let reconstruction:
const reconstruction:
| Reconstruction
| undefined = await reconstructionService.fetchReconstructionById(
+req.params.id,
Expand All @@ -194,7 +195,7 @@ export async function reconstructionFile(

debug('Check if reconstruction file exists.');
if (await storageAPI.fileExists(filePath)) {
let stream: Readable = await storageAPI.openReadStream(filePath);
const stream: Readable = await storageAPI.openReadStream(filePath);

res.setHeader(
'Content-Type',
Expand Down Expand Up @@ -225,9 +226,9 @@ export async function reconstructionBatch(
req: Request,
res: Response<Reconstruction[]>,
next: NextFunction
) {
): Promise<void> {
try {
let reconstruction:
const reconstruction:
| Reconstruction[]
| undefined = await reconstructionService.fetchReconstructionBatch(
+req.params.size || 10
Expand Down Expand Up @@ -257,7 +258,7 @@ export async function userReconstruction(
req: Request,
res: Response<PaginatedResult<Reconstruction>>,
next: NextFunction
) {
): Promise<void> {
try {
const paginationQuery: PaginationQuery = getPaginationQuery(req.query);

Expand Down Expand Up @@ -292,44 +293,75 @@ export async function create(
req: Request,
res: Response<ReconstructionCreationResponse>,
next: NextFunction
) {
const authReq: AuthRequestWithImages<
{},
): Promise<void> {
const authReq: AuthenticatedRequest<
unknown,
ReconstructionCreationResponse,
NewReconstruction
> = req as AuthRequestWithImages<
{},
unknown,
ReconstructionCreationResponse,
NewReconstruction
>;
try {
debug('Creating reconstruction.');
let reconstruction: Reconstruction = await reconstructionService.insertReconstruction(
const reconstruction: Reconstruction = await reconstructionService.insertReconstruction(
{
createdBy: authReq.user.id,
name: authReq.body.reconstruction_name,
}
);

if (reconstruction.id && authReq.images) {
debug('Adding images for reconstruction.');
res.json({
reconstruction: reconstruction,
});
} catch (err) {
debug('ERROR: %O', err);

next({
status: 500,
message: 'Error occurred while creating reconstruction.',
...err,
});
}
}

export async function addImage(
req: Request,
res: Response,
next: NextFunction
): Promise<void> {
const authReq: AuthRequestWithImages = req as AuthRequestWithImages;

try {
debug('Fetching requested reconstruction: %d', +req.params.id);
let reconstruction:
| Reconstruction
| undefined = await reconstructionService.fetchReconstructionById(
+req.params.id
);

if (reconstruction) {
debug('Adding new image for reconstruction.');
reconstruction = await reconstructionService.addImages(
reconstruction,
authReq.images
);

res.sendStatus(200);
return;
}

res.json({
reconstruction: reconstruction,
errors: authReq.fileValidationErrors,
next({
status: 404,
message: 'Reconstruction not found.',
});
} catch (err) {
debug('ERROR: %O', err);

next({
status: 500,
message: 'Error occurred while creating reconstruction.',
message: 'Error occurred while adding image to reconstruction.',
...err,
});
}
Expand All @@ -338,6 +370,7 @@ export async function create(
export default {
index,
create,
addImage,
reconstruction,
userReconstruction,
reconstructionFile,
Expand Down
6 changes: 0 additions & 6 deletions src/domain/ReconstructionCreationResponse.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,10 +8,6 @@
* properties:
* reconstruction:
* $ref: '#/components/schemas/Reconstruction'
* errors:
* type: array
* items:
* $ref: '#/components/schemas/ValidationErrorItem'
* responses:
* ReconstructionCreationResponse:
* description: User data in JSON response.
Expand All @@ -23,11 +19,9 @@
*/

import Reconstruction from '../models/Reconstruction';
import { ValidationErrorItem } from '../domain/validations';

export interface ReconstructionCreationResponse {
reconstruction?: Reconstruction;
errors?: ValidationErrorItem[];
}

export default ReconstructionCreationResponse;
18 changes: 9 additions & 9 deletions src/middlewares/uploadImage.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import Debug, { Debugger } from 'debug';
import { NextFunction, Request, Response } from 'express';
import { ParamsDictionary, Query } from 'express-serve-static-core';
import { NextFunction, Request, RequestHandler, Response } from 'express';

import config from '../config';
import Image from '../models/Image';
Expand All @@ -17,8 +17,8 @@ const debug: Debugger = Debug('threedify:middleware:uploadImage');

export interface RequestWithImages<
P = ParamsDictionary,
ResBody = any,
ReqBody = any,
ResBody = unknown,
ReqBody = unknown,
ReqQuery = Query
> extends Request<P, ResBody, ReqBody, ReqQuery> {
images: Image[];
Expand All @@ -27,8 +27,8 @@ export interface RequestWithImages<

export type AuthRequestWithImages<
P = ParamsDictionary,
ResBody = any,
ReqBody = any,
ResBody = unknown,
ReqBody = unknown,
ReqQuery = Query
> = AuthenticatedRequest<P, ResBody, ReqBody, ReqQuery> &
RequestWithImages<P, ResBody, ReqBody, ReqQuery>;
Expand All @@ -46,7 +46,7 @@ async function uploadImage(

if (fileName) {
debug('Insert image record.');
let image: Image = await imageService.insertImage({
const image: Image = await imageService.insertImage({
fileName: fileName,
mimetype: file.mimetype,
uploadedBy: authReq.user.id,
Expand All @@ -65,7 +65,7 @@ async function uploadImage(
}
}

export function uploadSingleImage(key: string) {
export function uploadSingleImage(key: string): RequestHandler[] {
return [
single(key),
async (
Expand Down Expand Up @@ -115,7 +115,7 @@ export function uploadSingleImage(key: string) {
];
}

export function uploadImages(key: string) {
export function uploadImages(key: string): RequestHandler[] {
return [
multiple(key),
async (
Expand All @@ -127,7 +127,7 @@ export function uploadImages(key: string) {
try {
debug('Uploading files for: %s', key);
if (req.files.length > 0) {
for (let file of req.files as Express.Multer.File[]) {
for (const file of req.files as Express.Multer.File[]) {
await uploadImage(file, key, authReq);
}

Expand Down
6 changes: 0 additions & 6 deletions src/middlewares/validateNewReconstruction.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@ import { ValidationResult } from 'joi';
import Debug, { Debugger } from 'debug';
import { NextFunction, Request, Response } from 'express';

import { cleanUp } from '../utils/uploads';
import { errorToResponse } from '../utils/joi';
import NewReconstruction from '../domain/NewReconstruction';
import { ValidationErrorResponse } from '../domain/validations';
Expand All @@ -28,11 +27,6 @@ export async function validateNewReconstruction(
res.status(422);
res.json(errorToResponse(result.error));

debug('Cleaning up temp files.');
for (let file of req.files as Express.Multer.File[]) {
await cleanUp(file.path);
}

return;
}

Expand Down
42 changes: 33 additions & 9 deletions src/routers/reconstructions.ts
Original file line number Diff line number Diff line change
@@ -1,18 +1,13 @@
import { Router } from 'express';

import { uploadImages } from '../middlewares/uploadImage';
import { uploadSingleImage } from '../middlewares/uploadImage';
import authenticateUser from '../middlewares/authenticateUser';
import ReconstructionController from '../controllers/reconstructions';
import { uploadReconstruction } from '../middlewares/uploadReconstruction';
import validateNewReconstruction from '../middlewares/validateNewReconstruction';

const router: Router = Router();

const imageUploadMiddlewares = uploadImages('images');
const reconstructionUploadMiddlewares = uploadReconstruction(
'reconstruction_file'
);

/**
* @swagger
*
Expand Down Expand Up @@ -106,12 +101,41 @@ router.get(
router.post(
'/create',
authenticateUser,
imageUploadMiddlewares[0],
validateNewReconstruction,
imageUploadMiddlewares[1],
ReconstructionController.create
);

/**
* @swagger
*
* /reconstructions/{id}/addImage:
* put:
* description: End point to add image to a reconstruction.
* parameters:
* - name: id
* in: path
* description: Id of reconstruction.
* responses:
* 200:
* description: OK
* content:
* text/plain:
* schema:
* type: string
* 422:
* $ref: '#/components/responses/ValidationErrorResponse'
* 404:
* $ref: '#/components/responses/HTTPError'
* 500:
* $ref: '#/components/responses/HTTPError'
*/
router.put(
'/:id/addImage',
authenticateUser,
uploadSingleImage('image'),
ReconstructionController.addImage
);

/**
* @swagger
*
Expand Down Expand Up @@ -196,7 +220,7 @@ router.put('/:id/failed', ReconstructionController.reconstructionFailed);
*/
router.put(
'/:id/success',
reconstructionUploadMiddlewares,
uploadReconstruction('reconstruction_file'),
ReconstructionController.reconstructionCompleted
);

Expand Down
Loading

0 comments on commit e43d2b6

Please sign in to comment.