calpoly-csai / api

Official API for the NIMBUS Voice Assistant accessible via HTTP REST protocol.
https://nimbus.api.calpolycsai.com/
GNU General Public License v3.0
9 stars 4 forks source link

Formatting Refactor Discussion #174

Open Waidhoferj opened 4 years ago

Waidhoferj commented 4 years ago

Objective

Reduce the scope of the database wrapper to interacting with the database.

Proposal

Require that all Entities have a validator and formatter class attached. By updating this class, we can make our error checking extensible and move most of the logic out of the database_wrapper.py file.

We have a top level initialization static method on each class called from_dict(data). All of the validation/formatting code in the database_wrapper could be reduced to the following:

try:
   entity = entity_type.from_dict(data)
except:
  #Handle errors
#Perform insert/update/delete

Internally this method would incorporate the following:

 validator = EntityTypeValidator()
formatter = EntityTypeFormatter()
  validator.validate(data) #Checks data for critical errors, raises exceptions handled above.
 formatted_data = formatter.format(data) #Casts data to correct type and fills in missing replaceable fields.
entity = EnitityType()
for key in formatted_data:
    setattr(entity, key, formatted_data[key])
return entity

Examples of validators and formatters can be found the the ./modules folder.

Benefits

Details

Currently the database has formatting and validation functionality baked into the wrapper. The code rigidly enforces that each Entity adheres to the keys defined in EXPECTED_KEYS_BY_ENTITY, but there are cases for the Nimbus Validator App where an ID needs to be passed instead of automatically generated. If I were to change the code in the validate_and_format_entity_data() function, there would likely be other breaking changes.

The proposed format would allow me to edit the QuestionAnswerPair formatter in isolation in order to field this new use case.

Waidhoferj commented 4 years ago

What do you all think about this new format?

Jason-Ku commented 4 years ago

image

In all seriousness, putting the validation/formatting burden on each Entity itself seems like a MUCH smarter move than trying to externally enforce it. Having an Entity interface that defines a validate and format method to call validators/formatters sounds like a really really smart move to me

Waidhoferj commented 4 years ago

It appears that SQLAlchemy doesn't make use of the constructor when it does its magic, so we can just use the entity constructor instead of a static from_dict() call. Gonna use this implementation in my next PR