Search code examples
pythonsqlalchemygraphene-python

python graphql translate uuid to slug


I'm using python, graphene, and sqlalchemy for an application. All of my models have an id field and a uuid field, generated like so

id = db.Column(
    db.Integer,
    primary_key=True,
    unique=True,
    nullable=False)

uuid = db.Column(
    UUID,
    unique=True,
    nullable=false,
    default=uuid.uuid4)

The uuid field will be used instead of the ID for security purposes, but the problem with uuid's is that they are too long, so to shorten them I use this method.

Now, I'm not entirely sure where this transformation from uuid to slug would happen. Would I have to define a @property on each of the models that would return the slug? Or would this happen in the graphql resolver functions, and if so, how would that be achieved?

All help appreciated, thank you!


Solution

  • It's pretty much up to you, there aren't any particular pros or cons to either. I guess if you plan on using the slug property elsewhere in your application it makes sense to put it on your model. If it's just going to be used in your GraphQL api then keep it in the resolvers.

    To implement it in Graphene you can do it like this:

    class User(graphene.ObjectType):
        id = graphene.ID(required=True)
    
        def resolve_id(user, info):
            return uuid_to_slug(user.uuid)