{
  "name": "ezGPT - Save JSON in PostgreSQL",
  "active": false,
  "nodes": [
    {
      "name": "Manual Trigger",
      "type": "n8n-nodes-base.manualTrigger",
      "typeVersion": 1,
      "parameters": {},
      "id": "pgjson-0",
      "position": [
        0,
        260
      ]
    },
    {
      "name": "Sample Document",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "parameters": {
        "mode": "runOnceForAllItems",
        "jsCode": "return [{ json: {\n  \"record_id\": \"DOC-001\",\n  \"document\": {\n    \"customer\": {\n      \"name\": \"Демо O'Connor\",\n      \"vip\": false\n    },\n    \"items\": [\n      {\n        \"sku\": \"SKU-001\",\n        \"quantity\": 2\n      },\n      {\n        \"sku\": \"SKU-002\",\n        \"quantity\": 0\n      }\n    ],\n    \"comment\": null\n  }\n} }];"
      },
      "id": "pgjson-1",
      "position": [
        240,
        260
      ]
    },
    {
      "name": "Check Document",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "parameters": {
        "mode": "runOnceForAllItems",
        "jsCode": "const items = $input.all();\nif (items.length !== 1) throw new Error('Expected one document item');\nconst row = items[0].json;\nfunction exactKeys(v, keys) {\n  return v !== null && typeof v === 'object' && !Array.isArray(v) &&\n    Object.keys(v).length === keys.length && keys.every(k => Object.hasOwn(v, k));\n}\nfunction text(v, max) {\n  return typeof v === 'string' && v.length <= max &&\n    !/[\\u0000-\\u001f\\u007f]/.test(v) &&\n    Buffer.from(v, 'utf8').toString('utf8') === v;\n}\nif (!exactKeys(row, ['record_id', 'document']) ||\n    typeof row.record_id !== 'string' || !/^DOC-\\d{3}$/.test(row.record_id)) {\n  throw new Error('Invalid document envelope');\n}\nconst d = row.document;\nif (!exactKeys(d, ['customer', 'items', 'comment']) ||\n    !exactKeys(d.customer, ['name', 'vip']) ||\n    !text(d.customer.name, 100) || !d.customer.name.trim() ||\n    typeof d.customer.vip !== 'boolean' ||\n    !Array.isArray(d.items) || d.items.length < 1 || d.items.length > 10 ||\n    !(d.comment === null || text(d.comment, 200))) {\n  throw new Error('Invalid document fields');\n}\nconst seen = new Set();\nfor (const item of d.items) {\n  if (!exactKeys(item, ['sku', 'quantity']) ||\n      typeof item.sku !== 'string' || !/^SKU-\\d{3}$/.test(item.sku) ||\n      seen.has(item.sku) || !Number.isSafeInteger(item.quantity) ||\n      item.quantity < 0 || item.quantity > 1000) throw new Error('Invalid document item');\n  seen.add(item.sku);\n}\nif (Buffer.byteLength(JSON.stringify(d), 'utf8') > 4096) throw new Error('Document too large');\nreturn [{ json: { record_id: row.record_id, document: d } }];"
      },
      "id": "pgjson-2",
      "position": [
        480,
        260
      ]
    },
    {
      "name": "Save JSON",
      "type": "n8n-nodes-base.postgres",
      "typeVersion": 2.6,
      "onError": "stopWorkflow",
      "parameters": {
        "resource": "database",
        "operation": "executeQuery",
        "query": "INSERT INTO app.documents (record_id, document)\nVALUES ($1, $2::jsonb)\nRETURNING record_id, document;",
        "options": {
          "queryReplacement": "={{ [$json.record_id, JSON.stringify($json.document)] }}"
        }
      },
      "id": "pgjson-3",
      "position": [
        720,
        260
      ]
    },
    {
      "name": "Verify JSON",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "parameters": {
        "mode": "runOnceForAllItems",
        "jsCode": "const source = $('Check Document').first().json;\nconst items = $input.all();\nfunction canonical(v) {\n  if (Array.isArray(v)) return v.map(canonical);\n  if (v !== null && typeof v === 'object') {\n    return Object.fromEntries(Object.keys(v).sort().map(k => [k, canonical(v[k])]));\n  }\n  return v;\n}\nif (items.length !== 1 || Object.keys(items[0].json).length !== 2 ||\n    items[0].json.record_id !== source.record_id ||\n    JSON.stringify(canonical(items[0].json.document)) !== JSON.stringify(canonical(source.document))) {\n  throw new Error('Stored JSON mismatch');\n}\nreturn [{ json: { record_id: source.record_id, document: items[0].json.document,\n  verified: true, external_send: false } }];"
      },
      "id": "pgjson-4",
      "position": [
        960,
        260
      ]
    }
  ],
  "connections": {
    "Manual Trigger": {
      "main": [
        [
          {
            "node": "Sample Document",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Sample Document": {
      "main": [
        [
          {
            "node": "Check Document",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Check Document": {
      "main": [
        [
          {
            "node": "Save JSON",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Save JSON": {
      "main": [
        [
          {
            "node": "Verify JSON",
            "type": "main",
            "index": 0
          }
        ]
      ]
    }
  },
  "settings": {
    "executionOrder": "v1"
  },
  "pinData": {}
}
