You've already forked hotpocket
BTHLABS-61: Service layer refactoring
A journey to fix `ValidationError` in Pocket imports turned service layer refactoring :D
This commit is contained in:
@@ -1,16 +1,39 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
from __future__ import annotations
|
||||
|
||||
import functools
|
||||
import typing
|
||||
|
||||
from bthlabs_jsonrpc_core.exceptions import BaseJSONRPCError
|
||||
from bthlabs_jsonrpc_django import (
|
||||
DjangoExecutor,
|
||||
DjangoJSONRPCSerializer,
|
||||
JSONRPCView as BaseJSONRPCView,
|
||||
)
|
||||
from django.core.exceptions import ValidationError
|
||||
import uuid6
|
||||
|
||||
from hotpocket_soa.exceptions.frontend import SOAError
|
||||
|
||||
|
||||
class SOAJSONRPCError(BaseJSONRPCError):
|
||||
ERROR_CODE = -32000
|
||||
ERROR_MESSAGE = 'SOA Error'
|
||||
|
||||
def to_rpc(self) -> dict:
|
||||
exception = typing.cast(SOAError, self.data)
|
||||
|
||||
code = (
|
||||
exception.code
|
||||
if exception.code is not None
|
||||
else self.ERROR_CODE
|
||||
)
|
||||
|
||||
return {
|
||||
'code': code,
|
||||
'message': exception.message or self.ERROR_MESSAGE,
|
||||
'data': exception.data,
|
||||
}
|
||||
|
||||
|
||||
class JSONRPCSerializer(DjangoJSONRPCSerializer):
|
||||
STRING_COERCIBLE_TYPES: typing.Any = (
|
||||
@@ -18,30 +41,6 @@ class JSONRPCSerializer(DjangoJSONRPCSerializer):
|
||||
uuid6.UUID,
|
||||
)
|
||||
|
||||
def serialize_value(self, value: typing.Any) -> typing.Any:
|
||||
if isinstance(value, ValidationError):
|
||||
result: typing.Any = None
|
||||
|
||||
if hasattr(value, 'error_dict') is True:
|
||||
result = {}
|
||||
for field, errors in value.error_dict.items():
|
||||
result[field] = [
|
||||
error.code
|
||||
for error
|
||||
in errors
|
||||
]
|
||||
elif hasattr(value, 'error_list') is True:
|
||||
result = [
|
||||
error.code
|
||||
for error in value.error_list
|
||||
]
|
||||
else:
|
||||
result = value.code
|
||||
|
||||
return self.serialize_value(result)
|
||||
|
||||
return super().serialize_value(value)
|
||||
|
||||
|
||||
class Executor(DjangoExecutor):
|
||||
serializer = JSONRPCSerializer
|
||||
@@ -49,3 +48,14 @@ class Executor(DjangoExecutor):
|
||||
|
||||
class JSONRPCView(BaseJSONRPCView):
|
||||
executor = Executor
|
||||
|
||||
|
||||
def wrap_soa_errors(func: typing.Callable) -> typing.Callable:
|
||||
@functools.wraps(func)
|
||||
def decorator(*args, **kwargs):
|
||||
try:
|
||||
return func(*args, **kwargs)
|
||||
except SOAError as exception:
|
||||
raise SOAJSONRPCError(exception)
|
||||
|
||||
return decorator
|
||||
|
||||
Reference in New Issue
Block a user