Return json from a mysql blob

Asked

Viewed 168 times

1

Good afternoon,

I have a json returning the data from a Mysql BD and one of the attributes is a BLOB. Below is the return to better understand what I would like to know.

[
{
    "id": 1,
    "name": "Onix",
    "description": "Completo",
    "price": 40000,
    "year": 2015,
    "color": "Prata",
    "brand": "Chevrolet",
    "model": "Hatch",
    "version": "1.8",
    "fuel": "Flex",
    "image": {
        "type": "Buffer",
        "data": [
            50,
            48,
            49,
            54,
            45,
            112,
            101,
            114,
            115,
            111,
            110,
            97,
            108,
            105,
            122,
            101,
            45,
            115,
            101,
            117,
            45,
            99,
            104,
            101,
            118,
            114,
            111,
            108,
            101,
            116,
            45,
            111,
            110,
            105,
            120,
            45,
            54,
            52,
            56,
            120,
            50,
            54,
            57,
            46,
            106,
            112,
            103
        ]
    },
    "createdAt": "2016-06-28T13:14:33.000Z",
    "updatedAt": "2016-06-28T13:14:33.000Z",
    "CategoryId": 2,
    "UserId": 1
}

]

Now with the return I would like to turn image.data into the image I saved in the bank.

The api that returns json has been implemented in nodejs.

Server-side

module.exports = app => {
  const Vehicles = app.db.models.Vehicles;

  app.route("/vehicles")
    .all(app.auth.authenticate())
    /**
     * @api {get} /vehicles List the user's vehicles
     * @apiGroup vehicles
     * @apiHeader {String} Authorization Token of authenticated vehicle
     * @apiHeaderExample {json} Header
     *    {"Authorization": "JWT xyz.abc.123.hgf"}
     * @apiSuccess {Object[]} vehicles Vehicle's list
     * @apiSuccess {Number} id Vehicle id
     * @apiSuccess {String} name Vehicle name
     * @apiSuccess {String} description Vehicle description
     * @apiSuccess {Number} price Vehicle price
     * @apiSuccess {Number} year Vehicle year
     * @apiSuccess {String} color Vehicle color
     * @apiSuccess {String} brand Vehicle brand
     * @apiSuccess {String} model Vehicle model
     * @apiSuccess {String} version Vehicle version
     * @apiSuccess {String} fuel Vehicle fuel
     * @apiSuccess {String} image Vehicle image
     * @apiSuccess {Date} updated_at Update's date
     * @apiSuccess {Date} created_at Register's date
     * @apiSuccess {Number} UserId User id
     * @apiSuccess {Number} CategoryId Category id
     * @apiSuccessExample {json} Success
     *    HTTP/1.1 200 OK
     *    [{
     *      "id": 1,
     *      "name": "Amarok",
     *      "description": "Ar condicionado, Ar quente, Direção Hidráulica",
     *      "price": 59000,
     *      "year": 2012,
     *      "color": "Prata",
     *      "brand": "Volkswagen",
     *      "model": "Turbo",
     *      "version": "2.0 4X4 CS 16V Intercooler",
     *      "fuel": "Diesel",
     *      "image": "QaWEssdrew1215AXccV515ZZaaa515MNhhggaaanncd545d151AAAa515a1a5a15",
     *      "updated_at": "2016-02-10T15:46:51.778Z",
     *      "created_at": "2016-02-10T15:46:51.778Z",
     *      "UserId": 1,
     *      "CategoryId": 1
     *    }]
     * @apiErrorExample {json} List error
     *    HTTP/1.1 412 Precondition Failed
     */
    .get((req, res) => {
      Vehicles.findAll({
        where: { UserId: req.user.id }
      })
      .then(result => res.json(result))
      .catch(error => {
        res.status(412).json({msg: error.message});
      });
    })
    /**
     * @api {post} /vehicles Register a new vehicle
     * @apiGroup vehicles
     * @apiHeader {String} Authorization Token of authenticated user
     * @apiHeaderExample {json} Header
     *    {"Authorization": "JWT xyz.abc.123.hgf"}
     * @apiParam {String} name Vehicle name
     * @apiParamExample {json} Input
     *      "name": "Amarok",
     *      "description": "Ar condicionado, Ar quente, Direção Hidráulica",
     *      "price": 59000,
     *      "year": 2012,
     *      "color": "Prata",
     *      "brand": "Volkswagen",
     *      "model": "Turbo",
     *      "version": "2.0 4X4 CS 16V Intercooler",
     *      "fuel": "Diesel",
     *      "image": "QaWEssdrew1215AXccV515ZZaaa515MNhhggaaanncd545d151AAAa515a1a5a15",
     * @apiSuccess {Number} id Vehicle id
     * @apiSuccess {String} name Vehicle name
     * @apiSuccess {String} description Vehicle description
     * @apiSuccess {Number} price Vehicle price
     * @apiSuccess {Number} year Vehicle year
     * @apiSuccess {String} color Vehicle color
     * @apiSuccess {String} brand Vehicle brand
     * @apiSuccess {String} model Vehicle model
     * @apiSuccess {String} version Vehicle version
     * @apiSuccess {String} fuel Vehicle fuel
     * @apiSuccess {String} image Vehicle image
     * @apiSuccess {Date} updated_at Update's date
     * @apiSuccess {Date} created_at Register's date
     * @apiSuccess {Number} UserId User id
     * @apiSuccess {Number} CategoryId Category id
     * @apiSuccessExample {json} Success
     *    HTTP/1.1 200 OK
     *    {
     *      "id": 1,
     *      "name": "Amarok",
     *      "description": "Ar condicionado, Ar quente, Direção Hidráulica",
     *      "price": 59000,
     *      "year": 2012,
     *      "color": "Prata",
     *      "brand": "Volkswagen",
     *      "model": "Turbo",
     *      "version": "2.0 4X4 CS 16V Intercooler",
     *      "fuel": "Diesel",
     *      "image": "QaWEssdrew1215AXccV515ZZaaa515MNhhggaaanncd545d151AAAa515a1a5a15",
     *      "updated_at": "2016-02-10T15:46:51.778Z",
     *      "created_at": "2016-02-10T15:46:51.778Z",
     *      "UserId": 1,
     *      "CategoryId": 1
     *    }
     * @apiErrorExample {json} Register error
     *    HTTP/1.1 412 Precondition Failed
     */
    .post((req, res) => {
      req.body.UserId = req.user.id;
      Vehicles.create(req.body)
        .then(result => res.json(result))
        .catch(error => {
          res.status(412).json({msg: error.message});
        });
    });

  app.route("/vehicles/:id")
    .all(app.auth.authenticate())
    /**
     * @api {get} /vehicles/:id Get a vehicle
     * @apiGroup vehicles
     * @apiHeader {String} Authorization Token of authenticated user
     * @apiHeaderExample {json} Header
     *    {"Authorization": "JWT xyz.abc.123.hgf"}
     * @apiParam {id} id Vehicle id
     * @apiSuccess {String} name Vehicle name
     * @apiSuccess {String} description Vehicle description
     * @apiSuccess {Number} price Vehicle price
     * @apiSuccess {Number} year Vehicle year
     * @apiSuccess {String} color Vehicle color
     * @apiSuccess {String} brand Vehicle brand
     * @apiSuccess {String} model Vehicle model
     * @apiSuccess {String} version Vehicle version
     * @apiSuccess {String} fuel Vehicle fuel
     * @apiSuccess {String} image Vehicle image
     * @apiSuccess {Date} updated_at Update's date
     * @apiSuccess {Date} created_at Register's date
     * @apiSuccess {Number} UserId User id
     * @apiSuccess {Number} CategoryId Category id
     * @apiSuccessExample {json} Success
     *    HTTP/1.1 200 OK
     *    {
     *      "id": 1,
     *      "name": "Amarok",
     *      "description": "Ar condicionado, Ar quente, Direção Hidráulica",
     *      "price": 59000,
     *      "year": 2012,
     *      "color": "Prata",
     *      "brand": "Volkswagen",
     *      "model": "Turbo",
     *      "version": "2.0 4X4 CS 16V Intercooler",
     *      "fuel": "Diesel",
     *      "image": "QaWEssdrew1215AXccV515ZZaaa515MNhhggaaanncd545d151AAAa515a1a5a15",
     *      "updated_at": "2016-02-10T15:46:51.778Z",
     *      "created_at": "2016-02-10T15:46:51.778Z",
     *      "UserId": 1,
     *      "CategoryId": 1
     *    }
     * @apiErrorExample {json} Vehicle not found error
     *    HTTP/1.1 404 Not Found
     * @apiErrorExample {json} Find error
     *    HTTP/1.1 412 Precondition Failed
     */
    .get((req, res) => {
      Vehicles.findOne({ where: {
        id: req.params.id,
        UserId: req.user.id
      }})
      .then(result => {
        if (result) {
          res.json(result);
        } else {
          res.sendStatus(404);
        }
      })
      .catch(error => {
        res.status(412).json({msg: error.message});
      });
    })
    /**
     * @api {put} /vehicles/:id Update a vehicle
     * @apiGroup vehicles
     * @apiHeader {String} Authorization Token of authenticated user
     * @apiHeaderExample {json} Header
     *    {"Authorization": "JWT xyz.abc.123.hgf"}
     * @apiParam {id} id Vehicle id
     * @apiParam {String} name Vehicle name
     * @apiParam {String} description Vehicle description
     * @apiParam {Number} price Vehicle price
     * @apiParam {Number} year Vehicle year
     * @apiParam {String} color Vehicle color
     * @apiParam {String} brand Vehicle brand
     * @apiParam {String} model Vehicle model
     * @apiParam {String} version Vehicle version
     * @apiParam {String} fuel Vehicle fuel
     * @apiParam {String} image Vehicle image
     * @apiParamExample {json} Input
     *    {
     *      "name": "Amarok",
     *      "description": "Ar condicionado, Ar quente, Direção Hidráulica",
     *      "price": 59000,
     *      "year": 2012,
     *      "color": "Prata",
     *      "brand": "Volkswagen",
     *      "model": "Turbo",
     *      "version": "2.0 4X4 CS 16V Intercooler",
     *      "fuel": "Diesel",
     *      "image": "QaWEssdrew1215AXccV515ZZaaa515MNhhggaaanncd545d151AAAa515a1a5a15"
     *    }
     * @apiSuccessExample {json} Success
     *    HTTP/1.1 204 No Content
     * @apiErrorExample {json} Update error
     *    HTTP/1.1 412 Precondition Failed
     */
    .put((req, res) => {
      Vehicles.update(req.body, { where: {
        id: req.params.id,
        UserId: req.user.id
      }})
      .then(result => res.sendStatus(204))
      .catch(error => {
        res.status(412).json({msg: error.message});
      });
    })
    /**
     * @api {delete} /vehicles/:id Remove a vehicle
     * @apiGroup vehicles
     * @apiHeader {String} Authorization Token of authenticated user
     * @apiHeaderExample {json} Header
     *    {"Authorization": "JWT xyz.abc.123.hgf"}
     * @apiParam {id} id Vehicle id
     * @apiSuccessExample {json} Success
     *    HTTP/1.1 204 No Content
     * @apiErrorExample {json} Delete error
     *    HTTP/1.1 412 Precondition Failed
     */
    .delete((req, res) => {
      Vehicles.destroy({ where: {
        id: req.params.id,
        UserId: req.user.id
      }})
      .then(result => res.sendStatus(204))
      .catch(error => {
        res.status(412).json({msg: error.message});
      });
    });
};

Client side

import FindMyCar from "../findmycar.js";
import Template from "../templates/vehicleForm.js";

class VehicleForm extends FindMyCar {
  constructor(body) {
    super();
    this.body = body;
  }
  render() {
    this.body.innerHTML = Template.render();
    this.body.querySelector("[data-name]").focus();
    this.addEventListener();
  }
  addEventListener() {
    this.formSubmit();
  }
  formSubmit() {
    const form = this.body.querySelector("form");
    form.addEventListener("submit", (e) => {
      e.preventDefault();
      const name = e.target.querySelector("[data-name]");
      const description = e.target.querySelector("[data-description]");
      const price = e.target.querySelector("[data-price]");
      const year = e.target.querySelector("[data-year]");
      const color = e.target.querySelector("[data-color]");
      const brand = e.target.querySelector("[data-brand]");
      const model = e.target.querySelector("[data-model]");
      const version = e.target.querySelector("[data-version]");
      const fuel = e.target.querySelector("[data-fuel]");
      const image = e.target.querySelector("[data-image]");
      const category = e.target.querySelector("[data-category]");

      const opts = {
        method: "POST",
        url: `${this.URL}/vehicles`,
        json: true,
        headers: {
          authorization: localStorage.getItem("token")
        },
        body: {
          name: name.value,
          description: description.value,
          price: price.value,
          year: year.value,
          color: color.value,
          brand: brand.value,
          model: model.value,
          version: version.value,
          fuel: fuel.value,
          image: image.value,
          CategoryId: category.value
        }
      };
      this.request(opts, (err, resp, data) => {
        if (err || resp.status === 412) {
          this.emit("error");
        } else {
          this.emit("submit");
        }
      });
    });
  }
}

module.exports = VehicleForm;

[]s

  • Before it spawned this JSON you’re treating the field somehow?

  • Good afternoon Marcelo, thank you for your attention. I am not, I select the direct image in an input type 'file' and send via POST to the bank.

  • You can post the code of how this is generated JSON?

  • Yes, I’ll ask the question.

No answers

Browser other questions tagged

You are not signed in. Login or sign up in order to post.