Stringify JSON object for SQL query in AWS AppSync

前端 未结 2 1185
误落风尘
误落风尘 2021-01-27 05:11

Question: How can I stringify JSON object for SQL statement in my Appsync velocity template?

Explanation: I have an Aurora RDS table tha

2条回答
  •  不要未来只要你来
    2021-01-27 06:02

    Solution 1:

    Thanks to @cyberwombat I was able to fix this issue. I am posting this as a reference if someone needs it.

    My serviceConfig object is not fixed and may change with time so I modified my resolver to make it more generic and it looks something like this:

    #set($serviceConfigMap = {})
    
    #foreach($key in $ctx.args.input.serviceConfig.keySet())
        $util.qr($serviceConfigMap.put("$key", $ctx.args.input.serviceConfig.get($key)))
    #end
    
    #set($serviceConfigMap = $util.toJson($serviceConfigMap))
    
    {
        "version": "2018-05-29",
        "statements": [
            "INSERT INTO b2b_service_catalog(service_name, service_config) VALUES ('$ctx.args.input.serviceName', '$util.escapeJavaScript($serviceConfigMap)') RETURNING service_id AS \"serviceId\", service_name AS \"serviceName\", service_config AS \"serviceConfig\"",
        ]
    }
    

    Old Solution:

    Here's how I solved this previously.

    I converted my resolver to Pipeline and created a simple Lambda function in NodeJS to stringify the JSON object. This is how my lambda function looks like:

    exports.handler = (event, context, callback) => {
    
        const response = {
            statusCode: 200,
            body: JSON.stringify(event.input.serviceConfig).replace(/\"/g, '\\\"'),
        };
        callback(null, response)
    };
    

    This is how serviceConfig looks like now and exactly how I wanted:

    {\"connectionType\":\"ftth\",\"maxUploadCapacity\":1}"
    

    I can now easily use it in my SQL statement within my resolver.

提交回复
热议问题