Representing logic as data in JSON

前端 未结 12 1501
眼角桃花
眼角桃花 2021-01-29 21:37

For business reasons we need to externalize some conditional logic into external files: preferably JSON.

A simple filter-by scenario could be handled by adding a node a

12条回答
  •  佛祖请我去吃肉
    2021-01-29 21:56

    Please check out (JSL)[https://www.npmjs.com/package/lib-jsl ]. It seems to fit the description given.

    Here is a sample :

    var JSL = require('lib-jsl');
    
    var bugs = [
        [{ bug : { desc: 'this is bug1 open', status : 'open' } }],
        [{ bug : { desc: 'this is bug2 resolved', status : 'resolved' } }],
        [{ bug : { desc: 'this is bug3 closed' , status : 'closed' } }],
        [{ bug : { desc: 'this is bug4 open', status : 'open' } }],
        [{ bug : { desc: 'this is bug5 resolved', status : 'resolved' } }],
        [{ bug : { desc: 'this is bug6 open', status : 'open' } }],
    
        [   { workInProgress : '$bug'},
            { bug : '$bug'},
            { $or : [
                { $bind : [ '$bug', { status : 'open'} ] },
                { $bind : [ '$bug', { status : 'resolved'} ] }
            ] }
        ]
    ];
    var query = [{workInProgress : '$wip'}]
    var transform = '$wip'
    var jsl = new JSL ({
        rules : bugs,
        query : query,
        transform : transform
    });
    var retval = jsl.run();
    console.log(JSON.stringify(retval, null,2));
    

    The response is :

    [
      {
        "desc": "this is bug1 open",
        "status": "open"
      },
      {
        "desc": "this is bug2 resolved",
        "status": "resolved"
      },
      {
        "desc": "this is bug4 open",
        "status": "open"
      },
      {
        "desc": "this is bug5 resolved",
        "status": "resolved"
      },
      {
        "desc": "this is bug6 open",
        "status": "open"
      }
    ]
    

    The main work is done by the query defined in the rule workInProgress :

    [   { workInProgress : '$bug'},
        { bug : '$bug'},
        { $or : [
            { $bind : [ '$bug', { status : 'open'} ] },
            { $bind : [ '$bug', { status : 'resolved'} ] }
        ] }
    ]
    

    This rule can be read as :

    To satisfy the query with workInProgress, we define a variable {workInProgress : '$bug'}, which we then proceed to match against all bugs in the database using the next part of the rule {bug : '$bug'}. This part matches all bugs since the shape of the object (it's keys: 'bug') matches the bug records in the database. The rule further asks the $bug variable to be $bind(ed) against patterns containing relevant status values (open and closed) within a $or. Only those bug records whose status value in $bug satisfies all parts of the rule's body qualify for the result.

    The result is finally transformed using the transform specification : transform : '$wip' which literally asks for an array of all values returned in the $wip variable of the query.

提交回复
热议问题