1
+ const User = require ( '../models/User' )
2
+ const Post = require ( '../models/Post' )
3
+ const fs = require ( 'fs' ) ;
4
+ const { jwt } = require ( '../config/jwt' ) ;
5
+ require ( 'dotenv' ) . config ( { path : './config/.env' } )
6
+
7
+ exports . createPost = async ( req , res , next ) => {
8
+ const { originalname, path} = req . file ;
9
+ const parts = originalname . split ( '.' ) ;
10
+ const ext = parts [ parts . length - 1 ] ;
11
+ const newPath = path + '.' + ext ;
12
+ fs . renameSync ( path , newPath ) ;
13
+
14
+ const { token} = req . cookies ;
15
+ jwt . verify ( token , process . env . jwtSecret , { } , async ( err , info ) => {
16
+ if ( err ) throw err ;
17
+ const { title, summary, content} = req . body ;
18
+ const postDoc = await Post . create ( {
19
+ title,
20
+ summary,
21
+ content,
22
+ cover :newPath ,
23
+ author :info . id ,
24
+ } ) ;
25
+ res . json ( postDoc ) ;
26
+ } ) ;
27
+ }
28
+
29
+ exports . updatePost = async ( req , res , next ) => {
30
+ let newPath = null ;
31
+ if ( req . file ) {
32
+ const { originalname, path} = req . file ;
33
+ const parts = originalname . split ( '.' ) ;
34
+ const ext = parts [ parts . length - 1 ] ;
35
+ newPath = path + '.' + ext ;
36
+ fs . renameSync ( path , newPath ) ;
37
+ }
38
+
39
+ const { token} = req . cookies ;
40
+ jwt . verify ( token , process . env . jwtSecret , { } , async ( err , info ) => {
41
+ if ( err ) throw err ;
42
+ const { id, title, summary, content} = req . body ;
43
+ let postDoc = await Post . findById ( id ) ;
44
+ const isAuthor = JSON . stringify ( postDoc . author ) === JSON . stringify ( info . id ) ;
45
+ if ( ! isAuthor ) {
46
+ return res . status ( 400 ) . json ( 'you are not the author' ) ;
47
+ }
48
+ postDoc = {
49
+ title,
50
+ summary,
51
+ content,
52
+ cover : newPath ? newPath : postDoc . cover ,
53
+ }
54
+
55
+ await Post . updateOne ( { _id : id } , postDoc ) ;
56
+
57
+ res . json ( postDoc ) ;
58
+ } ) ;
59
+ }
60
+
61
+ exports . getPosts = async ( req , res , next ) => {
62
+ res . json (
63
+ await Post . find ( )
64
+ . populate ( 'author' , [ 'username' ] )
65
+ . sort ( { createdAt : - 1 } )
66
+ . limit ( 20 )
67
+ ) ;
68
+ }
69
+
70
+ exports . getPost = async ( req , res , next ) => {
71
+ const { id} = req . params ;
72
+ const postDoc = await Post . findById ( id ) . populate ( 'author' , [ 'username' ] ) ;
73
+ res . json ( postDoc ) ;
74
+ }
0 commit comments