@@ -31,33 +31,33 @@ export default function createProject(req, res) {
31
31
}
32
32
33
33
// TODO: What happens if you don't supply any files?
34
- export function apiCreateProject ( req , res ) {
34
+ export async function apiCreateProject ( req , res ) {
35
35
const params = Object . assign ( { user : req . user . _id } , req . body ) ;
36
36
37
- function sendValidationErrors ( err , type , code = 422 ) {
37
+ const sendValidationErrors = ( err , type , code = 422 ) => {
38
38
res . status ( code ) . json ( {
39
39
message : `${ type } Validation Failed` ,
40
40
detail : err . message ,
41
41
errors : err . files
42
42
} ) ;
43
- }
43
+ } ;
44
44
45
45
// TODO: Error handling to match spec
46
- function sendFailure ( err ) {
46
+ const sendFailure = ( err ) => {
47
47
res . status ( 500 ) . end ( ) ;
48
- }
48
+ } ;
49
49
50
- function handleErrors ( err ) {
50
+ const handleErrors = ( err ) => {
51
51
if ( err instanceof FileValidationError ) {
52
52
sendValidationErrors ( err , 'File' , err . code ) ;
53
53
} else if ( err instanceof ProjectValidationError ) {
54
54
sendValidationErrors ( err , 'Sketch' , err . code ) ;
55
55
} else {
56
56
sendFailure ( ) ;
57
57
}
58
- }
58
+ } ;
59
59
60
- function checkUserHasPermission ( ) {
60
+ const checkUserHasPermission = ( ) => {
61
61
if ( req . user . username !== req . params . username ) {
62
62
console . log ( 'no permission' ) ;
63
63
const error = new ProjectValidationError (
@@ -67,35 +67,32 @@ export function apiCreateProject(req, res) {
67
67
68
68
throw error ;
69
69
}
70
- }
70
+ } ;
71
71
72
72
try {
73
73
checkUserHasPermission ( ) ;
74
74
75
+ if ( ! params . files || typeof params . files !== 'object' ) {
76
+ const error = new FileValidationError ( "'files' must be an object" ) ;
77
+ throw error ;
78
+ }
79
+
75
80
const model = toModel ( params ) ;
76
81
77
- return model
78
- . isSlugUnique ( )
79
- . then ( ( { isUnique, conflictingIds } ) => {
80
- if ( isUnique ) {
81
- return model . save ( ) . then ( ( newProject ) => {
82
- res . status ( 201 ) . json ( { id : newProject . id } ) ;
83
- } ) ;
84
- }
85
-
86
- const error = new ProjectValidationError (
87
- `Slug "${ model . slug } " is not unique. Check ${ conflictingIds . join (
88
- ', '
89
- ) } `
90
- ) ;
91
- error . code = 409 ;
92
-
93
- throw error ;
94
- } )
95
- . then ( checkUserHasPermission )
96
- . catch ( handleErrors ) ;
82
+ const { isUnique, conflictingIds } = await model . isSlugUnique ( ) ;
83
+
84
+ if ( ! isUnique ) {
85
+ const error = new ProjectValidationError (
86
+ `Slug "${ model . slug } " is not unique. Check ${ conflictingIds . join ( ', ' ) } `
87
+ ) ;
88
+ error . code = 409 ;
89
+
90
+ throw error ;
91
+ }
92
+
93
+ const newProject = await model . save ( ) ;
94
+ res . status ( 201 ) . json ( { id : newProject . id } ) ;
97
95
} catch ( err ) {
98
96
handleErrors ( err ) ;
99
- return Promise . reject ( err ) ;
100
97
}
101
98
}
0 commit comments