示例#1
0
        public CreateResult <WeightMeasurement> Create(WeightMeasurement measurement)
        {
            if (measurement is null)
            {
                return(CreateResult <WeightMeasurement> .BadRequest("Weight measurement failed to be created before storage."));
            }

            if (measurement.Unit == WeightMeasurement.Units.None)
            {
                return(CreateResult <WeightMeasurement> .BadRequest("Invalid weight unit provided. Valid values are: " + Enum <WeightMeasurement.Units> .GetValuesAsCSV()));
            }

            if (measurement.Weight < 0)
            {
                return(CreateResult <WeightMeasurement> .BadRequest("Weight must be a non-negative value."));
            }

            try
            {
                if (measurement.Id == Guid.Empty)
                {
                    measurement.Id = Guid.NewGuid();
                }
                else
                {
                    var existing = _store.Read(measurement.Id);
                    if (existing != null && existing.Id.Equals(measurement.Id))
                    {
                        return(CreateResult <WeightMeasurement> .Conflict("ID already exists"));
                    }
                }

                if (_store.Create(measurement))
                {
                    return(CreateResult <WeightMeasurement> .Created(measurement));
                }
                else
                {
                    return(CreateResult <WeightMeasurement> .InternalError("Failed to persist the measurement to a data store."));
                }
            }
            catch (Exception ex)
            {
                return(CreateResult <WeightMeasurement> .HandleException(ex));
            }
        }