|
| 1 | +import { Request, Response } from 'express'; |
| 2 | +import knex from '../database/connection'; |
| 3 | + |
| 4 | +class PointsController { |
| 5 | + async index(request: Request, response: Response) { |
| 6 | + const { city, uf, items } = request.query; |
| 7 | + |
| 8 | + const parsedItems = String(items) |
| 9 | + .split(',') |
| 10 | + .map((item) => Number(item.trim())); |
| 11 | + |
| 12 | + const points = await knex('points') |
| 13 | + .join('point_items', 'points.id', '=', 'point_items.point_id') |
| 14 | + .whereIn('point_items.item_id', parsedItems) |
| 15 | + .where('city', String(city)) |
| 16 | + .where('uf', String(uf)) |
| 17 | + .distinct() |
| 18 | + .select('points.*'); |
| 19 | + |
| 20 | + return response.json(points); |
| 21 | + } |
| 22 | + |
| 23 | + async show(request: Request, response: Response) { |
| 24 | + const { id } = request.params; |
| 25 | + |
| 26 | + const point = await knex('points').where('id', id).first(); |
| 27 | + |
| 28 | + if (!point) { |
| 29 | + return response.status(400).json({ message: 'Point not found.' }); |
| 30 | + } |
| 31 | + |
| 32 | + const items = await knex('items') |
| 33 | + .join('point_items', 'items.id', '=', 'point_items.item_id') |
| 34 | + .where('point_items.point_id', id) |
| 35 | + .select('items.title'); |
| 36 | + |
| 37 | + return response.json({ point, items }); |
| 38 | + } |
| 39 | + |
| 40 | + async create(request: Request, response: Response) { |
| 41 | + const { |
| 42 | + name, |
| 43 | + email, |
| 44 | + whatsapp, |
| 45 | + latitude, |
| 46 | + longitude, |
| 47 | + city, |
| 48 | + uf, |
| 49 | + items, |
| 50 | + } = request.body; |
| 51 | + |
| 52 | + const trx = await knex.transaction(); |
| 53 | + |
| 54 | + const point = { |
| 55 | + image: |
| 56 | + 'https://images.unsplash.com/photo-1542838132-92c53300491e?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=400&q=60', |
| 57 | + name, |
| 58 | + email, |
| 59 | + whatsapp, |
| 60 | + latitude, |
| 61 | + longitude, |
| 62 | + city, |
| 63 | + uf, |
| 64 | + }; |
| 65 | + |
| 66 | + const insertedIds = await trx('points').insert(point); |
| 67 | + |
| 68 | + const point_id = insertedIds[0]; |
| 69 | + |
| 70 | + const pointItems = items.map((item_id: number) => { |
| 71 | + return { |
| 72 | + item_id, |
| 73 | + point_id, |
| 74 | + }; |
| 75 | + }); |
| 76 | + |
| 77 | + await trx('point_items').insert(pointItems); |
| 78 | + |
| 79 | + await trx.commit(); |
| 80 | + |
| 81 | + return response.json({ |
| 82 | + id: point_id, |
| 83 | + ...point, |
| 84 | + }); |
| 85 | + } |
| 86 | +} |
| 87 | + |
| 88 | +export default PointsController; |
0 commit comments