post.controller.ts 8.61 KB
Newer Older
Lee Soobeom's avatar
Lee Soobeom committed
1
import { NextFunction, Request, Response } from "express";
Lee Soobeom's avatar
Lee Soobeom committed
2
import formidable, { Fields, Files } from "formidable";
Lee Soobeom's avatar
Lee Soobeom committed
3
import { TypedRequestAuth } from "./auth.controller";
Lee Soobeom's avatar
Lee Soobeom committed
4
import equals from "validator/lib/equals";
Lee Soobeom's avatar
Lee Soobeom committed
5
import { asyncWrap } from "../helpers";
Lee Soobeom's avatar
Lee Soobeom committed
6
7
import { postDb, userDb } from "../db";
import { TypedRequest } from "../types";
Lee Soobeom's avatar
Lee Soobeom committed
8
import { Types } from "mongoose";
Lee Soobeom's avatar
Lee Soobeom committed
9

Lee Soobeom's avatar
Lee Soobeom committed
10
11
12
13
14
15
16
17
18
19
20
export const userByPostId = (
  reqExp: Request,
  res: Response,
  next: NextFunction,
  postId: string
) => {
  const req = reqExp as TypedRequest;
  req.user = userDb.findUserByPostId(postId);
  next();
};

Lee Soobeom's avatar
Lee Soobeom committed
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
export const subTract = (oldSet: Set<string>, newSet: Set<string>) => {
  const keep = new Array<string>(); //유지
  const drop = new Array<string>(); //삭제
  const add = new Array<string>(); //추가

  oldSet.forEach((oldname) => {
    drop.push(oldname);
    newSet.forEach((newname) => {
      add.push(newname);
      if (oldname === newname) {
        keep.push(oldname);
      }
    });
  });

  const addSet = new Set(add);
  const newAdd = [...addSet];

  // console.log("before delete drop ", drop);
  // console.log("before delete add ", add);

  for (var i = 0; i < drop.length; i++) {
    for (var j = 0; j < keep.length; j++) {
      if (drop[i] === keep[j]) {
        drop.splice(i, 1);
      }
    }
  }

  for (var i = 0; i < newAdd.length; i++) {
    for (var j = 0; j < keep.length; j++) {
      if (newAdd[i] === keep[j]) {
        newAdd.splice(i, 1);
      }
    }
  }

  // console.log("spliced add", add);

  const dropSet = new Set(drop);
  const newDrop = [...dropSet];

  const reAddSet = new Set(newAdd);
  const reNewAdd = [...reAddSet];

  const res = {
    keep: keep,
    drop: newDrop,
    add: reNewAdd,
  };

  return res;
};

Lee Soobeom's avatar
Lee Soobeom committed
75
//Create
Lee Soobeom's avatar
Lee Soobeom committed
76
export const createFileAndPost = asyncWrap(async (reqExp, res, next) => {
Lee Soobeom's avatar
Lee Soobeom committed
77
  const req = reqExp as TypedRequestAuth<{ userId: string }>;
Lee Soobeom's avatar
Lee Soobeom committed
78

Lee Soobeom's avatar
Lee Soobeom committed
79
  const { userId } = req.auth;
Lee Soobeom's avatar
Lee Soobeom committed
80

Lee Soobeom's avatar
Lee Soobeom committed
81
82
83
84
  const form = formidable({
    uploadDir: "uploads",
    keepExtensions: true,
    multiples: true,
Lee Soobeom's avatar
Lee Soobeom committed
85
  });
Lee Soobeom's avatar
Lee Soobeom committed
86

Lee Soobeom's avatar
Lee Soobeom committed
87
  const fileIdArr = new Array();
Lee Soobeom's avatar
Lee Soobeom committed
88

Lee Soobeom's avatar
Lee Soobeom committed
89
  form.parse(req, async (err, fields, files) => {
Lee Soobeom's avatar
Lee Soobeom committed
90
91
92
93
94
95
96
97
98
    if (!Array.isArray(fields.title)) {
      const title = fields.title;
      if (!Array.isArray(fields.text)) {
        const text = fields.text;
        if (!Array.isArray(fields.theme)) {
          const theme = fields.theme;
          if (!Array.isArray(fields.city)) {
            const city = fields.city;

Lee Soobeom's avatar
Lee Soobeom committed
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
            if (Array.isArray(files.picture)) {
              for (var i = 0; i < files.picture.length; i++) {
                const originalfilename = files.picture?.[i].originalFilename;
                const newfilename = files.picture?.[i].newFilename;
                const filepath = files.picture?.[i].filepath;

                const filesRes = await postDb.createFilesRow(
                  originalfilename,
                  newfilename,
                  filepath
                );

                fileIdArr.push(filesRes);
              }
            } else if (!Array.isArray(files.picture)) {
              const originalfilename = files.picture.originalFilename;
              const newfilename = files.picture.newFilename;
              const filepath = files.picture.filepath;

              const filesRes = await postDb.createFilesRow(
                originalfilename,
                newfilename,
                filepath
              );

              fileIdArr.push(filesRes);
            } // file or one or more

            const postRes = await postDb.createPostRow({
Lee Soobeom's avatar
Lee Soobeom committed
128
129
130
131
132
133
134
              title,
              text,
              theme,
              city,
              date: Date.now(),
              counts: 0,
              user: userId,
Lee Soobeom's avatar
Lee Soobeom committed
135
136
              file: fileIdArr,
            });
Lee Soobeom's avatar
Lee Soobeom committed
137
138

            return res.json(postRes);
Lee Soobeom's avatar
Lee Soobeom committed
139
          }
Lee Soobeom's avatar
Lee Soobeom committed
140
141
142
143
        }
      }
    }
  });
144
});
Lee Soobeom's avatar
Lee Soobeom committed
145

Lee Soobeom's avatar
Lee Soobeom committed
146
//Read
Lee Soobeom's avatar
Lee Soobeom committed
147
148
149
150
151
152
export const getAllPost = asyncWrap(async (req, res) => {
  const posts = await postDb.getPosts();

  return res.json(posts);
});

Lee Soobeom's avatar
Lee Soobeom committed
153
154
155
156
157
158
159
export const getFiles = asyncWrap(async (req, res) => {
  const { postId } = req.params;
  const files = await postDb.getFilesByPostId(postId);

  return res.json(files);
});

Lee Soobeom's avatar
Lee Soobeom committed
160
//Update
Lee Soobeom's avatar
Lee Soobeom committed
161
162
163
164
165
166
167
168
169
170
export const addCounts = asyncWrap(async (req, res) => {
  const { postId } = req.params;
  const { counts } = req.body as {
    counts: number;
  };
  const updateCounts = await postDb.addOneCount(postId, counts);

  return res.json(updateCounts);
});

Lee Soobeom's avatar
Lee Soobeom committed
171
export const updateOnePost = asyncWrap(async (reqExp, res) => {
Lee Soobeom's avatar
Lee Soobeom committed
172
  const req = reqExp as TypedRequestAuth<{ userId: string }>;
Lee Soobeom's avatar
Lee Soobeom committed
173
  const { userId } = req.auth;
Lee Soobeom's avatar
Lee Soobeom committed
174
175
  const { postId } = req.params;

Lee Soobeom's avatar
Lee Soobeom committed
176
177
178
179
180
  const oldSet = new Set<string>();
  const newSet = new Set<string>();

  const fileIdArr = new Array<Types.ObjectId>();

Lee Soobeom's avatar
Lee Soobeom committed
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
  const form = formidable({
    uploadDir: "uploads",
    keepExtensions: true,
    multiples: true,
  });

  form.parse(req, async (err, fields, files) => {
    if (!Array.isArray(fields.title)) {
      const title = fields.title;
      if (!Array.isArray(fields.text)) {
        const text = fields.text;
        if (!Array.isArray(fields.theme)) {
          const theme = fields.theme;
          if (!Array.isArray(fields.city)) {
            const city = fields.city;
Lee Soobeom's avatar
Lee Soobeom committed
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217

            console.log("check files", files);

            if (files.picture === undefined || files.picture === null) {
              const postRes2 = await postDb.updatePostRow(
                {
                  title,
                  text,
                  theme,
                  city,
                  date: Date.now(),
                },
                postId
              );
              console.log("no files update", postRes2);
            } else {
              const oldFilesId = await postDb.getFilesByPostId(postId);
              if (!(oldFilesId === undefined)) {
                for (var i = 0; i < oldFilesId?.length; i++) {
                  const name = await postDb.getOriginalFileName(oldFilesId[i]);
                  if (!(name === undefined)) {
                    oldSet.add(name);
Lee Soobeom's avatar
Lee Soobeom committed
218
219
220
                  }
                }
              }
Lee Soobeom's avatar
Lee Soobeom committed
221
              console.log("OldSet", oldSet);
Lee Soobeom's avatar
Lee Soobeom committed
222
223
224
225

              if (Array.isArray(files.picture)) {
                for (var i = 0; i < files.picture.length; i++) {
                  const newFileName = files.picture?.[i].originalFilename;
Lee Soobeom's avatar
Lee Soobeom committed
226
                  if (!(newFileName === undefined || newFileName === null)) {
Lee Soobeom's avatar
Lee Soobeom committed
227
228
229
230
                    newSet.add(newFileName);
                  }
                }
              }
Lee Soobeom's avatar
Lee Soobeom committed
231
              console.log("NewSet", newSet);
Lee Soobeom's avatar
Lee Soobeom committed
232

Lee Soobeom's avatar
Lee Soobeom committed
233
234
              //유지, 삭제, 추가 구분하기
              const trdPart = subTract(oldSet, newSet);
Lee Soobeom's avatar
Lee Soobeom committed
235

Lee Soobeom's avatar
Lee Soobeom committed
236
237
238
239
240
241
242
243
244
              console.log("keep", trdPart.keep);
              console.log("drop", trdPart.drop);
              console.log("add", trdPart.add);

              // 삭제
              for (var i = 0; i < trdPart.drop.length; i++) {
                const dropRes = await postDb.deleteFileByName(trdPart.drop[i]);
                console.log("delete counts", dropRes);
              }
Lee Soobeom's avatar
Lee Soobeom committed
245

Lee Soobeom's avatar
Lee Soobeom committed
246
247
248
249
250
              //유지
              for (var i = 0; i < trdPart.keep.length; i++) {
                const keepRes = await postDb.findByName(trdPart.keep[i]);
                fileIdArr.push(keepRes[0]._id);
                // console.log("keep Id", keepRes[0]._id);
Lee Soobeom's avatar
Lee Soobeom committed
251
252
              }

Lee Soobeom's avatar
Lee Soobeom committed
253
              //추가
Lee Soobeom's avatar
Lee Soobeom committed
254
255
256
257
258
              if (Array.isArray(files.picture)) {
                for (var i = 0; i < files.picture.length; i++) {
                  const originalfilename = files.picture?.[i].originalFilename;
                  const newfilename = files.picture?.[i].newFilename;
                  const filepath = files.picture?.[i].filepath;
Lee Soobeom's avatar
Lee Soobeom committed
259
260
261
                  for (var j = 0; j < trdPart.add.length; j++) {
                    const check = trdPart.add[j];
                    if (originalfilename === check) {
Lee Soobeom's avatar
Lee Soobeom committed
262
263
264
265
266
267
                      const addRes = await postDb.createFilesRow(
                        originalfilename,
                        newfilename,
                        filepath
                      );

Lee Soobeom's avatar
Lee Soobeom committed
268
                      fileIdArr.push(addRes._id);
Lee Soobeom's avatar
Lee Soobeom committed
269
270
271
272
                    }
                  }
                }
              }
Lee Soobeom's avatar
Lee Soobeom committed
273
              console.log("all fileId", fileIdArr);
Lee Soobeom's avatar
Lee Soobeom committed
274

Lee Soobeom's avatar
Lee Soobeom committed
275
276
              //post정보 + file정보 update
              const postRes1 = await postDb.updatePostRow(
Lee Soobeom's avatar
Lee Soobeom committed
277
278
279
280
281
282
                {
                  title,
                  text,
                  theme,
                  city,
                  date: Date.now(),
Lee Soobeom's avatar
Lee Soobeom committed
283
                  file: fileIdArr,
Lee Soobeom's avatar
Lee Soobeom committed
284
285
286
287
288
289
290
291
292
                },
                postId
              );
            }
          }
        }
      }
    }
  });
Lee Soobeom's avatar
Lee Soobeom committed
293
});
Lee Soobeom's avatar
Lee Soobeom committed
294

Lee Soobeom's avatar
Lee Soobeom committed
295
// Delete
Lee Soobeom's avatar
Lee Soobeom committed
296
297
298
export const deleteOnePost = asyncWrap(async (req, res) => {
  const { postId } = req.params;

Lee Soobeom's avatar
Lee Soobeom committed
299
  const deleteCount = await postDb.deletePost(postId);
Lee Soobeom's avatar
Lee Soobeom committed
300

Lee Soobeom's avatar
Lee Soobeom committed
301
  return res.json(deleteCount);
Lee Soobeom's avatar
Lee Soobeom committed
302
});