jsonifier: allow json_key override by resolver

Quite handy to take full control of the final result.
pull/3205/head
Simone Orsi 2022-06-01 11:11:37 +02:00
parent 945f113735
commit 908a4c5956
3 changed files with 25 additions and 2 deletions

View File

@ -6,13 +6,18 @@ from odoo.tools.safe_eval import safe_eval
help_message = [
"Compute the result from 'value' by setting the variable 'result'.",
"For fields resolvers:",
"\n" "For fields resolvers:",
":param record: the record",
":param name: name of the field",
":param value: value of the field",
":param field_type: type of the field",
"For global resolvers:",
"\n" "For global resolvers:",
":param value: JSON dict",
":param record: the record",
"\n"
"In both types, you can override the final json key."
"\nTo achieve this, simply return a dict like: "
"\n{'result': {'_value': $value, '_json_key': $new_json_key}}",
]
@ -42,6 +47,7 @@ class FieldResolver(models.Model):
else: # param is a field
for record in records:
values = {
"record": record,
"value": record[param.name],
"name": param.name,
"field_type": param.type,

View File

@ -159,6 +159,11 @@ class Base(models.AbstractModel):
def _jsonify_record_handle_resolver(self, rec, field, resolver, json_key):
value = rec._jsonify_value(field, rec[field.name])
value = resolver.resolve(field, rec)[0] if resolver else value
if isinstance(value, dict) and "_json_key" in value and "_value" in value:
# Allow override of json_key.
# In this case,
# the final value must be encapsulated into _value key
value, json_key = value["_value"], value["_json_key"]
return value, json_key
def jsonify(self, parser, one=False):

View File

@ -1,4 +1,6 @@
# Copyright 2017 ACSONE SA/NV
# Copyright 2022 Camptocamp SA (http://www.camptocamp.com)
# Simone Orsi <simahawk@gmail.com>
# License LGPL-3.0 or later (http://www.gnu.org/licenses/lgpl).
from unittest import mock
@ -225,6 +227,16 @@ class TestParser(TransactionCase):
self.assertEqual(json["name_resolved"], "name_pidgin") # field resolver
self.assertEqual(json["X"], "X") # added by global resolver
def test_full_parser_resolver_json_key_override(self):
self.resolver.write(
{"python_code": """result = {"_json_key": "foo", "_value": record.id}"""}
)
parser = self.category_export.get_json_parser()
json = self.category.jsonify(parser)[0]
self.assertNotIn("name_resolved", json)
self.assertEqual(json["foo"], self.category.id) # field resolver
self.assertEqual(json["X"], "X") # added by global resolver
def test_simple_parser_translations(self):
"""The simple parser result should depend on the context language."""
parser = ["name"]