2019-04-04 11:18:22 +01:00
|
|
|
from flask import abort
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
class JSONModel():
|
|
|
|
|
|
|
|
|
|
ALLOWED_PROPERTIES = set()
|
|
|
|
|
|
|
|
|
|
def __init__(self, _dict):
|
|
|
|
|
# in the case of a bad request _dict may be `None`
|
|
|
|
|
self._dict = _dict or {}
|
|
|
|
|
|
|
|
|
|
def __bool__(self):
|
|
|
|
|
return self._dict != {}
|
|
|
|
|
|
2019-06-12 12:09:26 +01:00
|
|
|
def __hash__(self):
|
|
|
|
|
return hash(self.id)
|
|
|
|
|
|
|
|
|
|
def __eq__(self, other):
|
|
|
|
|
return self.id == other.id
|
|
|
|
|
|
2019-04-04 11:18:22 +01:00
|
|
|
def __getattr__(self, attr):
|
|
|
|
|
if attr in self.ALLOWED_PROPERTIES:
|
|
|
|
|
return self._dict[attr]
|
|
|
|
|
raise AttributeError('`{}` is not a {} attribute'.format(
|
|
|
|
|
attr,
|
|
|
|
|
self.__class__.__name__.lower(),
|
|
|
|
|
))
|
|
|
|
|
|
|
|
|
|
def _get_by_id(self, things, id):
|
|
|
|
|
try:
|
|
|
|
|
return next(thing for thing in things if thing['id'] == str(id))
|
|
|
|
|
except StopIteration:
|
|
|
|
|
abort(404)
|
Make user API client return JSON, not a model
The data flow of other bits of our application looks like this:
```
API (returns JSON)
⬇
API client (returns a built in type, usually `dict`)
⬇
Model (returns an instance, eg of type `Service`)
⬇
View (returns HTML)
```
The user API client was architected weirdly, in that it returned a model
directly, like this:
```
API (returns JSON)
⬇
API client (returns a model, of type `User`, `InvitedUser`, etc)
⬇
View (returns HTML)
```
This mixing of different layers of the application is bad because it
makes it hard to write model code that doesn’t have circular
dependencies. As our application gets more complicated we will be
relying more on models to manage this complexity, so we should make it
easy, not hard to write them.
It also means that most of our mocking was of the User model, not just
the underlying JSON. So it would have been easy to introduce subtle bugs
to the user model, because it wasn’t being comprehensively tested. A lot
of the changed lines of code in this commit mean changing the tests to
mock only the JSON, which means that the model layer gets implicitly
tested.
For those reasons this commit changes the user API client to return
JSON, not an instance of `User` or other models.
2019-05-23 15:27:35 +01:00
|
|
|
|
|
|
|
|
|
|
|
|
|
class InviteTokenError(Exception):
|
|
|
|
|
pass
|