post.controller.ts 10.5 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

            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 {
Lee Soobeom's avatar
Lee Soobeom committed
212
213
214
215
216
217
218
219
220
221
              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
222
223
                  }
                }
Lee Soobeom's avatar
Lee Soobeom committed
224
                console.log("OldSet", oldSet);
Lee Soobeom's avatar
Lee Soobeom committed
225

Lee Soobeom's avatar
Lee Soobeom committed
226
227
228
229
230
231
                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
232
233
                  }
                }
Lee Soobeom's avatar
Lee Soobeom committed
234
                console.log("NewSet", newSet);
Lee Soobeom's avatar
Lee Soobeom committed
235

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

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

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

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

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

Lee Soobeom's avatar
Lee Soobeom committed
272
                      fileIdArr.push(addRes._id);
Lee Soobeom's avatar
Lee Soobeom committed
273
274
275
                    }
                  }
                }
Lee Soobeom's avatar
Lee Soobeom committed
276
277
278
279
280
281
282
283
284
285
286
287
288
              } 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);
                    }
                  }
                }
                console.log("OldSet", oldSet);
Lee Soobeom's avatar
Lee Soobeom committed
289

Lee Soobeom's avatar
Lee Soobeom committed
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
                const newFileName = files.picture.originalFilename;
                if (!(newFileName === undefined || newFileName === null)) {
                  newSet.add(newFileName);
                }
                console.log("NewSet", newSet);

                //유지, 삭제, 추가 구분하기
                const trdPart = subTract(oldSet, newSet);

                //삭제
                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;
                for (var j = 0; j < trdPart.add.length; j++) {
                  const check = trdPart.add[j];
                  if (originalfilename === check) {
                    const addRes = await postDb.createFilesRow(
                      originalfilename,
                      newfilename,
                      filepath
                    );

                    fileIdArr.push(addRes._id);
                  }
                }
              }
Lee Soobeom's avatar
Lee Soobeom committed
324
            }
Lee Soobeom's avatar
Lee Soobeom committed
325
326
327
328
329
330
331
332
333
334
335
336
337
338
            console.log("all fileId", fileIdArr);

            //post정보 + file정보 update
            const postRes1 = await postDb.updatePostRow(
              {
                title,
                text,
                theme,
                city,
                date: Date.now(),
                file: fileIdArr,
              },
              postId
            );
Lee Soobeom's avatar
Lee Soobeom committed
339
340
341
342
343
          }
        }
      }
    }
  });
Lee Soobeom's avatar
Lee Soobeom committed
344
});
Lee Soobeom's avatar
Lee Soobeom committed
345

Lee Soobeom's avatar
Lee Soobeom committed
346
// Delete
Lee Soobeom's avatar
Lee Soobeom committed
347
348
349
export const deleteOnePost = asyncWrap(async (req, res) => {
  const { postId } = req.params;

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

Lee Soobeom's avatar
Lee Soobeom committed
352
  return res.json(deleteCount);
Lee Soobeom's avatar
Lee Soobeom committed
353
});