All files / server/api/locations locations.api.js

100% Statements 38/38
100% Branches 5/5
100% Functions 10/10
100% Lines 38/38
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 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 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 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 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244          1x   1x 1x 1x 1x 1x 1x     1x             1x   5x   2x 2x   2x               1x   8x   7x   7x 4x     7x   7x               1x 2x               1x   6x   4x 4x   4x 3x     4x               1x 1x 1x               1x     14x                     8x 8x                                     11x 11x                                                                                                                                                                                                                                  
/**
 * Locations management API.
 *
 * @module server/api/locations
 */
const serialize = require('express-serializer');
 
const Location = require('../../models/location');
const { fetcher, route } = require('../utils/api');
const { bbox: filterByBbox } = require('../utils/filters');
const { validateRequestBody, validateValue } = require('../utils/validation');
const { point: validateGeoJsonPoint } = require('../validators/geojson');
const policy = require('./locations.policy');
 
// API resource name (used in some API errors)
exports.resourceName = 'location';
 
/**
 * Creates a new location.
 *
 * @function
 */
exports.create = route(async (req, res) => {
 
  await validateLocation(req);
 
  const location = policy.parse(req.body);
  await location.save();
 
  res.status(201).send(await serialize(req, location, policy));
});
 
/**
 * Lists locations ordered by name.
 *
 * @function
 */
exports.list = route(async (req, res) => {
 
  await validateListRequest(req);
 
  let query = new Location();
 
  if (req.query.bbox) {
    query = filterByBbox(query, req.query.bbox);
  }
 
  const locations = await query.orderBy('name').orderBy('created_at').fetchAll();
 
  res.send(await serialize(req, locations.models, policy));
});
 
/**
 * Retrieves a single location.
 *
 * @function
 */
exports.retrieve = route(async (req, res) => {
  res.send(await serialize(req, req.location, policy));
});
 
/**
 * Updates a location.
 *
 * @function
 */
exports.update = route(async (req, res) => {
 
  await validateLocation(req, true);
 
  const location = req.location;
  policy.parse(req.body, location);
 
  if (location.hasChanged()) {
    await location.save();
  }
 
  res.send(await serialize(req, location, policy));
});
 
/**
 * Deletes a location.
 *
 * @function
 */
exports.destroy = route(async (req, res) => {
  await req.location.destroy();
  res.sendStatus(204);
});
 
/**
 * Middleware that fetches the location identified by the ID in the URL.
 *
 * @function
 */
exports.fetchLocation = fetcher({
  model: Location,
  resourceName: exports.resourceName,
  coerce: id => id.toLowerCase(),
  validate: 'uuid'
});
 
/**
 * Validates the query parameters of a request to list locations.
 *
 * @param {Request} req - An Express request object.
 * @returns {Promise<ValidationErrorBundle>} - A promise that will be resolved if the request is valid, or rejected with a bundle of errors if it is invalid.
 */
function validateListRequest(req) {
  return validateValue(req, 422, function() {
    return this.parallel(
      this.validate(
        this.query('bbox'),
        this.while(this.isSet()),
        this.notBlank(),
        this.bboxString()
      )
    );
  });
}
 
/**
 * Validates the location in the request body.
 *
 * @param {Request} req - An Express request object.
 * @param {boolean} [patchMode=false] - If true, only properties that are set will be validated (i.e. a partial update with a PATCH request).
 * @returns {Promise<ValidationErrorBundle>} - A promise that will be resolved if the location is valid, or rejected with a bundle of errors if it is invalid.
 */
function validateLocation(req, patchMode = false) {
  return validateRequestBody(req, function() {
    return this.parallel(
      this.validate(
        this.json('/name'),
        this.if(patchMode, this.while(this.isSet())),
        this.required(),
        this.type('string'),
        this.notBlank(),
        this.string(1, 150)
      ),
      this.validate(
        this.json('/shortName'),
        this.while(this.isSetAndNotNull()),
        this.type('string'),
        this.notBlank(),
        this.string(1, 30)
      ),
      this.validate(
        this.json('/description'),
        this.if(patchMode, this.while(this.isSet())),
        this.required(),
        this.type('string'),
        this.notBlank(),
        this.string(1, 2000)
      ),
      this.validate(
        this.json('/phone'),
        this.if(patchMode, this.while(this.isSet())),
        this.required(),
        this.type('string'),
        this.notBlank(),
        this.string(1, 20)
      ),
      this.validate(
        this.json('/photoUrl'),
        this.if(patchMode, this.while(this.isSet())),
        this.required(),
        this.type('string'),
        this.notBlank(),
        this.string(1, 500)
      ),
      this.validate(
        this.json('/siteUrl'),
        this.if(patchMode, this.while(this.isSet())),
        this.required(),
        this.type('string'),
        this.notBlank(),
        this.string(1, 500)
      ),
      this.validate(
        this.json('/geometry'),
        this.if(patchMode, this.while(this.isSet())),
        this.required(),
        this.geoJsonPoint()
      ),
      this.validate(
        this.json('/properties'),
        this.while(this.isSet()),
        this.type('object')
      ),
      this.validate(
        this.json('/address'),
        this.if(patchMode, this.while(this.isSet())),
        this.required(),
        this.type('object'),
        this.parallel(
          this.validate(
            this.json('/street'),
            this.if(patchMode, this.while(this.isSet())),
            this.required(),
            this.type('string'),
            this.notBlank(),
            this.string(1, 150),
            this.notBlank()
          ),
          this.validate(
            this.json('/number'),
            this.while(this.isSetAndNotNull()),
            this.type('string'),
            this.string(1, 10),
            this.notBlank()
          ),
          this.validate(
            this.json('/zipCode'),
            this.if(patchMode, this.while(this.isSet())),
            this.required(),
            this.type('string'),
            this.notBlank(),
            this.string(1, 15),
            this.notBlank()
          ),
          this.validate(
            this.json('/city'),
            this.if(patchMode, this.while(this.isSet())),
            this.required(),
            this.type('string'),
            this.notBlank(),
            this.string(1, 100),
            this.notBlank()
          ),
          this.validate(
            this.json('/state'),
            this.if(patchMode, this.while(this.isSet())),
            this.required(),
            this.type('string'),
            this.notBlank(),
            this.string(1, 30),
            this.notBlank()
          )
        )
      )
    );
  });
}