简体   繁体   English

INVALID_REQUEST_ERROR - VERSION_MISMATCH - 对象版本与最新的数据库版本不匹配

[英]INVALID_REQUEST_ERROR - VERSION_MISMATCH - Object version does not match latest database version

I am trying to do update some data in my square inventory using node's square-connect package like this:我正在尝试使用节点的square-connect包更新我的 square 清单中的一些数据,如下所示:

I am using a firebase functions function that executes the code anytime the firebase database gets updated (that is what export.updateItem is for, this is the function that executes, and returns a snapshot of the data that got updated):我正在使用firebase functions函数,该函数在 firebase 数据库更新时执行代码(这就是export.updateItem的用途,这是执行的函数,并返回更新数据的快照):

exports.updateItem = functions.firestore
    .document('items/{itemId}')
    .onUpdate((change, context) => {
        // Get an object representing the document
        // e.g. {'name': 'Marie', 'age': 66}
        const newValue = change.after.data();
        const previousValue = change.before.data();

        var params = {
            query: {
                exact_query: {
                    attribute_name: "sku",
                    attribute_value: newValue.barcode
                }
            }
        }

        api.searchCatalogObjects(params).then(function(data) {
            console.log('API called successfully in searchFor IDS. Returned data: ' + JSON.stringify(data));

            var dat = data;

            var variation = {
                type: "ITEM_VARIATION",
                id: dat.objects[0].id,
                present_at_all_locations: true,
                item_variation_data: {
                  item_id: dat.objects[0].item_variation_data.item_id,
                  name: "Regular",
                  pricing_type: "FIXED_PRICING",
                  price_money: {
                    amount: Number(newValue.price) * 100,
                    currency: "USD",
                  },
                  sku: newValue.barcode,
                  track_inventory: true
                }
            };

            var item = {
              type: 'ITEM',
              id: dat.objects[0].item_variation_data.item_id,
              item_data: {
                name: newValue.barcode,
                description: newValue.description,
                variations: [variation]
              }
            };

            const idempotencyKey = require('crypto').randomBytes(32).toString('hex');
            var body = {
              idempotency_key: idempotencyKey,
              batches: [{
                objects: [item]
              }]
            };


            api.batchUpsertCatalogObjects(body).then(function(data) {
                console.log('API called successfully in update from EditItem. Returned data: ' + JSON.stringify(data));

                if(newValue.quantity != previousValue.quantity) {

                    var res = data;
                    var variationId = res.objects[0].item_data.variations[0].id;

                    locationApi.listLocations().then(function(data) {
                      console.log('API called successfully in locationApi. Returned data: ' + JSON.stringify(data));

                        var dat = data;
                        var locationId = dat.locations[0].id; // String | The ID of the item's associated location.

                         // String | The ID of the variation to adjust inventory information for.

                        //var body = new SquareConnect.V1AdjustInventoryRequest(); // V1AdjustInventoryRequest | An object containing the fields to POST for the request.  See the corresponding object definition for field details.

                        var adjustBody = {
                            quantity_delta: Number(newValue.quantity) - Number(previousValue.quantity),
                            adjustment_type: 'MANUAL_ADJUST'
                        }

                        inventoryApi.adjustInventory(locationId, variationId, adjustBody).then(function(data) {
                          console.log('API called successfully in inventoryApi. Returned data: ' + JSON.stringify(data));
                        }, function(error) {
                          console.error(error);
                        });
                    }, function(error) {
                      console.error(error);
                    });
                }
            }, function(error) {
              console.error(error);
            });

        }, function(error) {
          console.error(error);
        });

      return null;
    });

The firebase functions log reads like this: firebase 函数日志如下所示:

9:02:19.367 AM
updateItem
Function execution started
9:02:21.309 AM
updateItem
Function execution took 1944 ms, finished with status: 'ok'
9:02:31.834 AM
updateItem
API called successfully in searchFor IDS. Returned data: {"objects":[{"type":"ITEM_VARIATION","id":"6WNRO7PULPW7Z4QL73FEVITU","updated_at":"2018-08-14T00:53:50.645Z","version":1534208030645,"is_deleted":false,"present_at_all_locations":true,"item_variation_data":{"item_id":"SUW2HSXCNSERMTGERY4Y54TD","name":"Regular","sku":"0637792505002","ordinal":0,"pricing_type":"FIXED_PRICING","price_money":{"amount":100,"currency":"USD"},"location_overrides":[{"location_id":"JN6S37JH6M1Z2","track_inventory":true}],"track_inventory":true}}]}
9:02:47.035 AM
updateItem
 { Error: Bad Request
    at Request.callback (/user_code/node_modules/square-connect/node_modules/superagent/lib/node/index.js:675:11)
    at /user_code/node_modules/square-connect/node_modules/superagent/lib/node/index.js:883:18
    at Stream.<anonymous> (/user_code/node_modules/square-connect/node_modules/superagent/lib/node/parsers/json.js:16:7)
    at emitNone (events.js:86:13)
    at Stream.emit (events.js:185:7)
    at Unzip.<anonymous> (/user_code/node_modules/square-connect/node_modules/superagent/lib/node/unzip.js:53:12)
    at emitNone (events.js:91:20)
    at Unzip.emit (events.js:185:7)
    at endReadableNT (_stream_readable.js:974:12)
    at _combinedTickCallback (internal/process/next_tick.js:80:11)
  status: 400,
  response: 
   Response {
     domain: null,
     _events: {},
     _eventsCount: 0,
     _maxListeners: undefined,
     res: 
      IncomingMessage {
        _readableState: [Object],
        readable: false,
        domain: null,
        _events: [Object],
        _eventsCount: 3,
        _maxListeners: undefined,
        socket: [Object],
        connection: [Object],
        httpVersionMajor: 1,
        httpVersionMinor: 1,
        httpVersion: '1.1',
        complete: true,
        headers: [Object],
        rawHeaders: [Object],
        trailers: {},
        rawTrailers: [],
        upgrade: false,
        url: '',
        method: null,
        statusCode: 400,
        statusMessage: 'Bad Request',
        client: [Object],
        _consuming: true,
        _dumped: false,
        req: [Object],
        setEncoding: [Function],
        on: [Function],
        text: '{"errors":[{"category":"INVALID_REQUEST_ERROR","code":"VERSION_MISMATCH","detail":"Object version does not match latest database version.","field":"version"}]}',
        read: [Function] },
     request: 
      Request {
        domain: null,
        _events: {},
        _eventsCount: 0,
        _maxListeners: undefined,
        _agent: false,
        _formData: null,
        method: 'POST',
        url: 'https://connect.squareup.com/v2/catalog/batch-upsert',
        _header: [Object],
        header: [Object],
        writable: true,
        _redirects: 0,
        _maxRedirects: 5,
        cookies: '',
        qs: {},
        qsRaw: [],
        _redirectList: [],
        _streamRequest: false,
        _timeout: 60000,
        _responseTimeout: 0,
        _data: [Object],
        req: [Object],
        protocol: 'https:',
        host: 'connect.squareup.com',
        _endCalled: true,
        _callback: [Function],
        res: [Object],
        response: [Circular],
        called: true },
     req: 
      ClientRequest {
        domain: null,
        _events: [Object],
        _eventsCount: 3,
        _maxListeners: undefined,
        output: [],
        outputEncodings: [],
        outputCallbacks: [],
        outputSize: 0,
        writable: true,
        _last: true,
        upgrading: false,
        chunkedEncoding: false,
        shouldKeepAlive: false,
        useChunkedEncodingByDefault: true,
        sendDate: false,
        _removedHeader: [Object],
        _contentLength: 526,
        _hasBody: true,
        _trailer: '',
        finished: true,
        _headerSent: true,
        socket: [Object],
        connection: [Object],
        _header: 'POST /v2/catalog/batch-upsert HTTP/1.1\r\nHost: connect.squareup.com\r\nAccept-Encoding: gzip, deflate\r\nUser-Agent: Square-Connect-Javascript/2.20180712.1\r\nAuthorization: Bearer sq0atp-on5KcHDr0dhlbefU0EwVwg\r\nSquare-Version: 2018-07-12\r\nContent-Type: application/json\r\nAccept: application/json\r\nContent-Length: 526\r\nConnection: close\r\n\r\n',
        _headers: [Object],
        _headerNames: [Object],
        _onPendingData: null,
        agent: [Object],
        socketPath: undefined,
        timeout: undefined,
        method: 'POST',
        path: '/v2/catalog/batch-upsert',
        _ended: true,
        parser: null,
        res: [Object] },
     text: '{"errors":[{"category":"INVALID_REQUEST_ERROR","code":"VERSION_MISMATCH","detail":"Object version does not match latest database version.","field":"version"}]}',
     body: { errors: [Object] },
     files: undefined,
     buffered: true,
     headers: 
      { 'content-encoding': 'gzip',
        'content-type': 'application/json',
        'square-version': '2018-07-12',
        vary: 'Origin, Accept-Encoding',
        'x-content-type-options': 'nosniff',
        'x-download-options': 'noopen',
        'x-frame-options': 'SAMEORIGIN',
        'x-permitted-cross-domain-policies': 'none',
        'x-xss-protection': '1; mode=block',
        date: 'Tue, 14 Aug 2018 13:02:39 GMT',
        'keep-alive': 'timeout=60',
        'strict-transport-security': 'max-age=631152000',
        'content-length': '159',
        connection: 'close' },
     header: 
      { 'content-encoding': 'gzip',
        'content-type': 'application/json',
        'square-version': '2018-07-12',
        vary: 'Origin, Accept-Enco

In the Bad request info you can see the error is in the text attribute:Bad request信息中,您可以看到错误在text属性中:

text: '{"errors":[{"category":"INVALID_REQUEST_ERROR","code":"VERSION_MISMATCH","detail":"Object version does not match latest database version.","field":"version"}]}'

When I look up data, I see a version attribute that comes with, for example, a square ITEM_VARIATION , that looks like:当我查找数据时,我看到一个版本属性,例如一个方形ITEM_VARIATION ,它看起来像:

"version":1534208030645

You can see it in the object after this text in the output above:您可以在上面输出中的此文本之后的对象中看到它:

API called successfully in searchFor IDS.在searchFor IDS 中成功调用API。 Returned data:返回数据:

It appears in the data that gets returned when I search for the ITEM_VARIATION .它出现在我搜索ITEM_VARIATION时返回的数据中。 I have tried putting this field and value into the batchUpsertCatalogObjects request but it doesn't seem to help - I believe I received another error trying to do this (I can't remember what it was, or find it in the logs right now).我曾尝试将此字段和值放入batchUpsertCatalogObjects请求中,但它似乎没有帮助 - 我相信我在尝试执行此操作时收到了另一个错误(我不记得它是什么,或者现在在日志中找到它) .

Any help would be greatly appreciated.任何帮助将不胜感激。

UPDATE更新

I tried adding version: dat.objects[0].version to the item object but it didn't help.我尝试将version: dat.objects[0].versionitem对象,但没有帮助。

UPDATE更新

I tried this:我试过这个:

var variationObj = dat.objects[0];

variationObj.item_variation_data.price_money =  {amount: Number(newValue.price) * 100, currency: 'USD'};

var item = {
              type: 'ITEM',
              id: dat.objects[0].item_variation_data.item_id,
              item_data: {
                name: newValue.barcode,
                description: newValue.description,
                variations: [variationObj]
           }
};

I still get the same error though - even when I use the same exact object that is being returned to me from the query.尽管如此,我仍然遇到相同的错误 - 即使我使用从查询返回给我的完全相同的对象。

UPDATE更新

Above update is what worked - see answer.以上更新是有效的 - 请参阅答案。

What seemed to do the trick was taking the object I needed directly from the response and editing it like responseObj.xxxxxxx = xxxxxxxx - instead of trying to create one myself using {} notation - and then passing that object through as the necessary parameter. 似乎能解决问题的技巧是直接从响应中获取我需要的对象,并像responseObj.xxxxxxx = xxxxxxxx一样对其进行编辑-而不是尝试使用{}表示法创建自己的对象-然后将该对象作为必需的参数传递。 Also, firebase deploy seems to need to be rerun sometimes to actually have the changes take effect. 而且,有时似乎需要重新运行firebase deploy才能真正使更改生效。

Is also seemed like I needed to use uspsertCatalogObject to upload the ITEM and ITEM_VARIATION separately, instead of including the ITEM_VARITION in the ITEM 's variations field, or using batchUpsertCatalogObject with both the ITEM and ITEM_VARIATION contained in the batches array - that seemed to not work either. 也好像我需要使用uspsertCatalogObject上传ITEMITEM_VARIATION ,而不是包括单独, ITEM_VARITIONITEMvariations领域,或者使用batchUpsertCatalogObject有两个ITEMITEM_VARIATION包含在batches阵列-这似乎不工作无论是。

I see this is an old question, but I come across it now and I had the same error.我看到这是一个老问题,但我现在遇到了它并且我遇到了同样的错误。 So I hope it helps someone in the future.所以我希望它可以帮助将来的某个人。

According to Square API documentation:根据 Square API 文档:

Version => The version of the object.版本 => 对象的版本。 When updating an object, the version supplied must match the version in the database, otherwise, the write will be rejected as conflicting.更新对象时,提供的版本必须与数据库中的版本匹配,否则写入将被拒绝为冲突。

So when you get the object you will have a property with the version number, you just need to pass that value when updating the catalog object.因此,当您获得对象时,您将拥有一个带有版本号的属性,您只需在更新目录对象时传递该值。 (in both, product and variant) (在产品和变体中)

Here is an example of the simplest JSON request to update a product catalog using the version field.以下是使用版本字段更新产品目录的最简单 JSON 请求示例。

    "object": {
      "type": "ITEM",
      },
      "id": "7R55G27F2LHH2VUJ7ZONKWRA",
      "item_data": {
        "product_type": "REGULAR",
        "variations": [
          {
            "id": "GQTI2KPZHXNM33QJAJJLAGWC",
            "type": "ITEM_VARIATION",
            "item_data": {
              "name": "cenas variant",
              "product_type": "REGULAR"
            },
            "item_variation_data": {
              "track_inventory": false,
              "pricing_type": "FIXED_PRICING",
              "price_money": {
                "amount": 50,
                "currency": "AUD"
              }
            },
            "version": 1637854673484
          }
        ],
        "name": "UPDATE DE PRODUTO"
      },
      "version": 1637854673484
    },
    "idempotency_key": "ffe8498d-6313-45c8-b772-13c2dbc77b4b"
  }'

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM