Exemplo n.º 1
0
    def _create_linked_handler(self, model):
        # the related action type
        related_action_type = get_crud_action('delete', model, status=success_status())
        # the action handler
        async def action_handler(action_type, payload, notify=True, **kwds):
            """
                an action handler to remove related entries in the
                connection db.
            """
            # if the action designates a successful delete of the model
            if action_type == related_action_type:
                # the id of the deleted model
                related_id = payload['id']
                # the query for matching fields
                matching_records = getattr(self.model, model_service_name(model)) == related_id
                ids = [model.id for model in self.model.filter(matching_records)]
                # find the matching records
                self.model.delete().where(matching_records).execute()

                # if we are supposed to notify
                if notify:
                    # notify of the related delete
                    await self.event_broker.send(
                        action_type=get_crud_action('delete', self.model, status=success_status()),
                        payload=ids
                    )


        # pass the action handler
        return action_handler
Exemplo n.º 2
0
async def query_handler(service, action_type, payload, props, **kwds):
    """
        This action handler interprets the payload as a query to be executed
        by the api gateway service.
    """
    # check that the action type indicates a query
    if action_type == query_action_type():
        print('encountered query event {!r} '.format(payload))
        # perform the query
        result = await parse_string(payload,
            service.object_resolver,
            service.connection_resolver,
            service.mutation_resolver,
            obey_auth=False
        )

        # the props for the reply message
        reply_props = {'correlation_id': props['correlation_id']} if 'correlation_id' in props else {}

        # publish the success event
        await service.event_broker.send(
            payload=result,
            action_type=change_action_status(action_type, success_status()),
            **reply_props
        )
Exemplo n.º 3
0
async def query_handler(service, action_type, payload, props, **kwds):
    """
        This action handler interprets the payload as a query to be executed
        by the api gateway service.
    """
    # check that the action type indicates a query
    if action_type == query_action_type():
        print('encountered query event {!r} '.format(payload))
        # perform the query
        result = await parse_string(payload,
                                    service.object_resolver,
                                    service.connection_resolver,
                                    service.mutation_resolver,
                                    obey_auth=False)

        # the props for the reply message
        reply_props = {
            'correlation_id': props['correlation_id']
        } if 'correlation_id' in props else {}

        # publish the success event
        await service.event_broker.send(payload=result,
                                        action_type=change_action_status(
                                            action_type, success_status()),
                                        **reply_props)
Exemplo n.º 4
0
    def _create_linked_handler(self, model):
        # the related action type
        related_action_type = get_crud_action('delete',
                                              model,
                                              status=success_status())

        # the action handler
        async def action_handler(action_type, payload, notify=True, **kwds):
            """
                an action handler to remove related entries in the
                connection db.
            """
            # if the action designates a successful delete of the model
            if action_type == related_action_type:
                # the id of the deleted model
                related_id = payload['id']
                # the query for matching fields
                matching_records = getattr(
                    self.model, model_service_name(model)) == related_id
                ids = [
                    model.id for model in self.model.filter(matching_records)
                ]
                # find the matching records
                self.model.delete().where(matching_records).execute()

                # if we are supposed to notify
                if notify:
                    # notify of the related delete
                    await self.event_broker.send(action_type=get_crud_action(
                        'delete', self.model, status=success_status()),
                                                 payload=ids)

        # pass the action handler
        return action_handler
Exemplo n.º 5
0
    async def action_handler(service, action_type, payload, props, **kwds):
        # if the payload represents a new instance of `model`
        if action_type == get_crud_action('read', name or Model):
            # the props of the message
            message_props = {}
            # if there was a correlation id in the request
            if 'correlation_id' in props:
                # make sure it ends up in the reply
                message_props['correlation_id'] = props['correlation_id']

            try:
                # resolve the query using the service schema
                resolved = service.schema.execute(payload)
                # create the string response
                response = json.dumps({
                    'data': {key:value for key,value in resolved.data.items()},
                    'errors': resolved.errors
                })

                # publish the success event
                await service.event_broker.send(
                    payload=response,
                    action_type=change_action_status(action_type, success_status()),
                    **message_props
                )

            # if something goes wrong
            except Exception as err:
                # publish the error as an event
                await service.event_broker.send(
                    payload=str(err),
                    action_type=change_action_status(action_type, error_status()),
                    **message_props
                )
Exemplo n.º 6
0
    async def action_handler(service,
                             action_type,
                             payload,
                             props,
                             notify=True,
                             **kwds):
        # if the payload represents a new instance of `Model`
        if action_type == get_crud_action('create', name or Model):
            # print('handling create for ' + name or Model)
            try:
                # the props of the message
                message_props = {}
                # if there was a correlation id in the request
                if 'correlation_id' in props:
                    # make sure it ends up in the reply
                    message_props['correlation_id'] = props['correlation_id']

                # for each required field
                for requirement in Model.required_fields():

                    # save the name of the field
                    field_name = requirement.name
                    # ensure the value is in the payload
                    # TODO: check all required fields rather than failing on the first
                    if not field_name in payload and field_name != 'id':
                        # yell loudly
                        raise ValueError(
                            "Required field not found in payload: %s" %
                            field_name)

                # create a new model
                new_model = Model(**payload)

                # save the new model instance
                new_model.save()

                # if we need to tell someone about what happened
                if notify:
                    # publish the scucess event
                    await service.event_broker.send(
                        payload=ModelSerializer().serialize(new_model),
                        action_type=change_action_status(
                            action_type, success_status()),
                        **message_props)

            # if something goes wrong
            except Exception as err:
                # if we need to tell someone about what happened
                if notify:
                    # publish the error as an event
                    await service.event_broker.send(
                        payload=str(err),
                        action_type=change_action_status(
                            action_type, error_status()),
                        **message_props)
                # otherwise we aren't supposed to notify
                else:
                    # raise the exception normally
                    raise err
Exemplo n.º 7
0
    async def action_handler(service, action_type, payload, props, notify=True, **kwds):
        # if the payload represents a new instance of `Model`
        if action_type == get_crud_action('update', name or Model):
            try:
                # the props of the message
                message_props = {}
                # if there was a correlation id in the request
                if 'correlation_id' in props:
                    # make sure it ends up in the reply
                    message_props['correlation_id'] = props['correlation_id']


                # grab the nam eof the primary key for the model
                pk_field = Model.primary_key()

                # make sure there is a primary key to id the model
                if not pk_field.name in payload:
                    # yell loudly
                    raise ValueError("Must specify the pk of the model when updating")

                # grab the matching model
                model = Model.select().where(pk_field == payload[pk_field.name]).get()

                # remove the key from the payload
                payload.pop(pk_field.name, None)

                # for every key,value pair
                for key, value in payload.items():
                    # TODO: add protection for certain fields from being
                    # changed by the api
                    setattr(model, key, value)

                # save the updates
                model.save()

                # if we need to tell someone about what happened
                if notify:
                    # publish the scucess event
                    await service.event_broker.send(
                        payload=ModelSerializer().serialize(model),
                        action_type=change_action_status(action_type, success_status()),
                        **message_props
                    )

            # if something goes wrong
            except Exception as err:
                # if we need to tell someone about what happened
                if notify:
                    # publish the error as an event
                    await service.event_broker.send(
                        payload=str(err),
                        action_type=change_action_status(action_type, error_status()),
                        **message_props
                    )
                # otherwise we aren't supposed to notify
                else:
                    # raise the exception normally
                    raise err
Exemplo n.º 8
0
    async def action_handler(service, action_type, payload, props, notify=True, **kwds):
        # if the payload represents a new instance of `Model`
        if action_type == get_crud_action('create', name or Model):
            # print('handling create for ' + name or Model)
            try:
                # the props of the message
                message_props = {}
                # if there was a correlation id in the request
                if 'correlation_id' in props:
                    # make sure it ends up in the reply
                    message_props['correlation_id'] = props['correlation_id']

                # for each required field
                for requirement in Model.required_fields():

                    # save the name of the field
                    field_name = requirement.name
                    # ensure the value is in the payload
                    # TODO: check all required fields rather than failing on the first
                    if not field_name in payload and field_name != 'id':
                        # yell loudly
                        raise ValueError(
                            "Required field not found in payload: %s" %field_name
                        )

                # create a new model
                new_model = Model(**payload)

                # save the new model instance
                new_model.save()

                # if we need to tell someone about what happened
                if notify:
                    # publish the scucess event
                    await service.event_broker.send(
                        payload=ModelSerializer().serialize(new_model),
                        action_type=change_action_status(action_type, success_status()),
                        **message_props
                    )

            # if something goes wrong
            except Exception as err:
                # if we need to tell someone about what happened
                if notify:
                    # publish the error as an event
                    await service.event_broker.send(
                        payload=str(err),
                        action_type=change_action_status(action_type, error_status()),
                        **message_props
                    )
                # otherwise we aren't supposed to notify
                else:
                    # raise the exception normally
                    raise err
Exemplo n.º 9
0
    async def action_handler(service,
                             action_type,
                             payload,
                             props,
                             notify=True,
                             **kwds):
        # if the payload represents a new instance of `model`
        if action_type == get_crud_action('delete', name or Model):
            try:
                # the props of the message
                message_props = {}
                # if there was a correlation id in the request
                if 'correlation_id' in props:
                    # make sure it ends up in the reply
                    message_props['correlation_id'] = props['correlation_id']
                # the id in the payload representing the record to delete
                record_id = payload['id'] if 'id' in payload else payload['pk']
                # get the model matching the payload
                try:
                    model_query = Model.select().where(
                        Model.primary_key() == record_id)
                except KeyError:
                    raise RuntimeError(
                        "Could not find appropriate id to remove service record."
                    )
                # remove the model instance
                model_query.get().delete_instance()
                # if we need to tell someone about what happened
                if notify:
                    # publish the success event
                    await service.event_broker.send(
                        payload='{"status":"ok"}',
                        action_type=change_action_status(
                            action_type, success_status()),
                        **message_props)

            # if something goes wrong
            except Exception as err:
                # if we need to tell someone about what happened
                if notify:
                    # publish the error as an event
                    await service.event_broker.send(
                        payload=str(err),
                        action_type=change_action_status(
                            action_type, error_status()),
                        **message_props)
                # otherwise we aren't supposed to notify
                else:
                    # raise the exception normally
                    raise err
Exemplo n.º 10
0
    async def action_handler(service, action_type, payload, props, notify=True, **kwds):
        # if the payload represents a new instance of `model`
        if action_type == get_crud_action('delete', name or Model):
            try:
                # the props of the message
                message_props = {}
                # if there was a correlation id in the request
                if 'correlation_id' in props:
                    # make sure it ends up in the reply
                    message_props['correlation_id'] = props['correlation_id']
                # the id in the payload representing the record to delete
                record_id = payload['id'] if 'id' in payload else payload['pk']
                # get the model matching the payload
                try:
                    model_query = Model.select().where(Model.primary_key() == record_id)
                except KeyError:
                    raise RuntimeError("Could not find appropriate id to remove service record.")
                # remove the model instance
                model_query.get().delete_instance()
                # if we need to tell someone about what happened
                if notify:
                    # publish the success event
                    await service.event_broker.send(
                        payload='{"status":"ok"}',
                        action_type=change_action_status(action_type, success_status()),
                        **message_props
                    )

            # if something goes wrong
            except Exception as err:
                # if we need to tell someone about what happened
                if notify:
                    # publish the error as an event
                    await service.event_broker.send(
                        payload=str(err),
                        action_type=change_action_status(action_type, error_status()),
                        **message_props
                    )
                # otherwise we aren't supposed to notify
                else:
                    # raise the exception normally
                    raise err
Exemplo n.º 11
0
 def test_has_success_status(self):
     # create the success status
     status = success_status()
     # make sure its a string
     assert isinstance(status, str)
Exemplo n.º 12
0
 def test_has_success_status(self):
     # create the success status
     status = success_status()
     # make sure its a string
     assert isinstance(status, str)
Exemplo n.º 13
0
    async def action_handler(service,
                             action_type,
                             payload,
                             props,
                             notify=True,
                             **kwds):
        # if the payload represents a new instance of `Model`
        if action_type == get_crud_action('update', name or Model):
            try:
                # the props of the message
                message_props = {}
                # if there was a correlation id in the request
                if 'correlation_id' in props:
                    # make sure it ends up in the reply
                    message_props['correlation_id'] = props['correlation_id']

                # grab the nam eof the primary key for the model
                pk_field = Model.primary_key()

                # make sure there is a primary key to id the model
                if not pk_field.name in payload:
                    # yell loudly
                    raise ValueError(
                        "Must specify the pk of the model when updating")

                # grab the matching model
                model = Model.select().where(
                    pk_field == payload[pk_field.name]).get()

                # remove the key from the payload
                payload.pop(pk_field.name, None)

                # for every key,value pair
                for key, value in payload.items():
                    # TODO: add protection for certain fields from being
                    # changed by the api
                    setattr(model, key, value)

                # save the updates
                model.save()

                # if we need to tell someone about what happened
                if notify:
                    # publish the scucess event
                    await service.event_broker.send(
                        payload=ModelSerializer().serialize(model),
                        action_type=change_action_status(
                            action_type, success_status()),
                        **message_props)

            # if something goes wrong
            except Exception as err:
                # if we need to tell someone about what happened
                if notify:
                    # publish the error as an event
                    await service.event_broker.send(
                        payload=str(err),
                        action_type=change_action_status(
                            action_type, error_status()),
                        **message_props)
                # otherwise we aren't supposed to notify
                else:
                    # raise the exception normally
                    raise err