post.controller.ts 11 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
export const SubTract = (oldSet: Set<string>, newSet: Set<string>) => {
Lee Soobeom's avatar
Lee Soobeom committed
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
  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

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

            if (files.picture === undefined || files.picture === null) {
Lee Soobeom's avatar
Lee Soobeom committed
200
              const postRes1 = await postDb.updatePostRow(
Lee Soobeom's avatar
Lee Soobeom committed
201
202
203
204
205
206
207
208
209
                {
                  title,
                  text,
                  theme,
                  city,
                  date: Date.now(),
                },
                postId
              );
Lee Soobeom's avatar
Lee Soobeom committed
210
211
              console.log("no files update", postRes1);
              return res.json(postRes1);
Lee Soobeom's avatar
Lee Soobeom committed
212
            } else {
Lee Soobeom's avatar
Lee Soobeom committed
213
214
215
216
217
218
219
220
221
222
              if (Array.isArray(files.picture)) {
                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
223
224
                  }
                }
Lee Soobeom's avatar
Lee Soobeom committed
225
                console.log("OldSet", oldSet);
Lee Soobeom's avatar
Lee Soobeom committed
226

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

Lee Soobeom's avatar
Lee Soobeom committed
237
                //유지, 삭제, 추가 구분하기
Lee Soobeom's avatar
Lee Soobeom committed
238
                const trdPart = SubTract(oldSet, newSet);
Lee Soobeom's avatar
Lee Soobeom committed
239

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

Lee Soobeom's avatar
Lee Soobeom committed
244
245
246
247
248
249
250
                // 삭제
                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
251

Lee Soobeom's avatar
Lee Soobeom committed
252
253
254
255
256
257
                //유지
                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
258

Lee Soobeom's avatar
Lee Soobeom committed
259
                //추가
Lee Soobeom's avatar
Lee Soobeom committed
260
261
262
263
                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
264
265
266
                  for (var j = 0; j < trdPart.add.length; j++) {
                    const check = trdPart.add[j];
                    if (originalfilename === check) {
Lee Soobeom's avatar
Lee Soobeom committed
267
268
269
270
271
272
                      const addRes = await postDb.createFilesRow(
                        originalfilename,
                        newfilename,
                        filepath
                      );

Lee Soobeom's avatar
Lee Soobeom committed
273
                      fileIdArr.push(addRes._id);
Lee Soobeom's avatar
Lee Soobeom committed
274
275
276
                    }
                  }
                }
Lee Soobeom's avatar
Lee Soobeom committed
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293

                console.log("all fileId", fileIdArr);

                //post정보 + file정보 update
                const postRes2 = await postDb.updatePostRow(
                  {
                    title,
                    text,
                    theme,
                    city,
                    date: Date.now(),
                    file: fileIdArr,
                  },
                  postId
                );
                console.log("plural files update", postRes2);
                return res.json(postRes2);
Lee Soobeom's avatar
Lee Soobeom committed
294
295
296
              } else {
                const oldFilesId = await postDb.getFilesByPostId(postId);
                if (!(oldFilesId === undefined)) {
Lee Soobeom's avatar
Lee Soobeom committed
297
298
299
                  const name = await postDb.getOriginalFileName(oldFilesId[0]);
                  if (!(name === undefined)) {
                    oldSet.add(name);
Lee Soobeom's avatar
Lee Soobeom committed
300
301
302
                  }
                }
                console.log("OldSet", oldSet);
Lee Soobeom's avatar
Lee Soobeom committed
303

Lee Soobeom's avatar
Lee Soobeom committed
304
305
306
307
308
309
310
                const newFileName = files.picture.originalFilename;
                if (!(newFileName === undefined || newFileName === null)) {
                  newSet.add(newFileName);
                }
                console.log("NewSet", newSet);

                //유지, 삭제, 추가 구분하기
Lee Soobeom's avatar
Lee Soobeom committed
311
                const trdPart = SubTract(oldSet, newSet);
Lee Soobeom's avatar
Lee Soobeom committed
312

Lee Soobeom's avatar
Lee Soobeom committed
313
314
                console.log("add part", trdPart.add);

Lee Soobeom's avatar
Lee Soobeom committed
315
316
317
318
319
320
321
322
323
324
325
326
                //삭제
                for (var i = 0; i < trdPart.drop.length; i++) {
                  const dropRes = await postDb.deleteFileByName(
                    trdPart.drop[i]
                  );
                  console.log("delete counts", dropRes);
                }

                //추가
                const originalfilename = files.picture.originalFilename;
                const newfilename = files.picture.newFilename;
                const filepath = files.picture.filepath;
Lee Soobeom's avatar
Lee Soobeom committed
327
328
329
330
331
332
                if (originalfilename === trdPart.add[0]) {
                  const addRes = await postDb.createFilesRow(
                    originalfilename,
                    newfilename,
                    filepath
                  );
Lee Soobeom's avatar
Lee Soobeom committed
333

Lee Soobeom's avatar
Lee Soobeom committed
334
                  fileIdArr.push(addRes._id);
Lee Soobeom's avatar
Lee Soobeom committed
335
                }
Lee Soobeom's avatar
Lee Soobeom committed
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352

                console.log("all fileId", fileIdArr);

                //post정보 + file정보 update
                const postRes3 = await postDb.updatePostRow(
                  {
                    title,
                    text,
                    theme,
                    city,
                    date: Date.now(),
                    file: fileIdArr,
                  },
                  postId
                );
                console.log("singular file update", postRes3);
                return res.json(postRes3);
Lee Soobeom's avatar
Lee Soobeom committed
353
              }
Lee Soobeom's avatar
Lee Soobeom committed
354
355
356
357
358
359
            }
          }
        }
      }
    }
  });
Lee Soobeom's avatar
Lee Soobeom committed
360
});
Lee Soobeom's avatar
Lee Soobeom committed
361

Lee Soobeom's avatar
Lee Soobeom committed
362
// Delete
Lee Soobeom's avatar
Lee Soobeom committed
363
364
365
export const deleteOnePost = asyncWrap(async (req, res) => {
  const { postId } = req.params;

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

Lee Soobeom's avatar
Lee Soobeom committed
368
  return res.json(deleteCount);
Lee Soobeom's avatar
Lee Soobeom committed
369
});