Source of Truth - Part 2

Following on from yesterday's post about determining the source of truth I thought I would follow up with two examples of potential solutions.

First up we have the case where we two sources, an API and the database. In this case we want know deterministically which data should take priority, therefore we can process the data from the API in the background and and save the relevant updated fields to the database. This keeps the overall system flow of data simpler.

Here would be an example of an update function:


def update_from_api(instance, data_from_api):
  # Example where API takes priority
  # This assumes data types match up completely.
  # This could fail if the updated field from the API contains an empty string
  instance.updated = data_from_api.get('updated', instance.updated)

  # Example where the DB takes priority if the DB has data.
  if not instance.created:
    instance.created = data_from_api.get('created', instance.created)

  instance.save()

Tomorrow we will look at a more complex example where the user would need to be involved in the solution.