라우팅 구성
1 2 3 4 5 |
... routes.put('/hero', AdminController.modifyHero); export default routes; |
컨트롤러 구성
power 를 업데이트하는 것은 삭제된것도 있을것이고 추가된것도 있을것이기 때문에, 아예 기존것을 지우고, 새로 insert 하는 편이 낫다.
쿼리문을 동적으로 구성하기 위해서 updateOption을 조건에 따라서 동적으로 구성한다.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 |
... static modifyHero = async (req, res) => { const {id, name, email, sex, country, address, powers, photo} = req.body; const updateOption = {}; if (name) updateOption['name'] = name; if (email) updateOption['email'] = email; if (sex) updateOption['sex'] = sex; if (country) updateOption['country'] = country; if (address) updateOption['address'] = address; if (photo) updateOption['photo'] = photo; // Hero update await getConnection().createQueryBuilder().update(Hero) .set(updateOption) .where("id = :id", {id}) .execute() // delete old powers await getConnection() .createQueryBuilder() .delete() .from(Power) .where("heroId = :id", { id }) .execute(); // insert powers if (powers && powers.length > 0) { const hero = new Hero(); hero.id = id; const newPowers = powers.map(power => { const p = new Power(); p.name = power; p.hero = hero; // relation key return p; }) // bulk insert await getConnection().createQueryBuilder().insert().into(Power).values(newPowers).execute(); } const result = new ResultVo(0, 'success'); res.send(result); } |