2015-01-02 4 views
0

일부 구문 분석 데이터의 테이블에 일부 개체가 저장됩니다. 하지만 제약 조건을 추가하거나 삽입하려는 데이터가 고유해야합니다. 다음 코드와 같은 것을 사용하고 있습니다. 하지만 나는 (페이스 북 API에서 얻는) eventId가 내 테이블에서 고유하다는 것을 보증하기를 원하기 때문에 중복 정보가 없다. 작동하게하는 가장 좋은 방법은 무엇입니까?구문 분석 데이터의 열에 제약 조건 추가

var Event = Parse.Object.extend("Event"); 
var event = new Event(); 
event.set("eventId", id); 
event.set("eventName", name); 

event.save(null, { 
    success: function(event) { 
    console.log('New object created with objectId: ' + event.eventId); 
    }, 
    error: function(event, error) { 
    console.log('Failed to create new object, with error code: ' + error.message); 
    } 
}); 

업데이트 :

나는 HttpRequest를 내부를 호출하고 있습니다. 다음은 내가 가지고있는 것인데, 그 안의 beforeSave를 호출하는 방법을 알아낼 수 없다.

Parse.Cloud.define("hello", function(request, response) { 

    var query = new Parse.Query("Location"); 
    query.find({ 
     success: function(results) { 
      console.log(results); 
     var totalResults = results.length; 
     var completedResults = 0; 
     var completion = function() { 
      response.success("Finished"); 
     }; 

      for (var i = 0; i < totalResults; ++i){ 

      locationId = results[i].get("locationFbId"); 

      Parse.Cloud.httpRequest({ 
       url: 'https://graph.facebook.com/v2.2/'+locationId+'/events?access_token='+accessToken, 
       success: function(httpResponse) { 
       console.log(httpResponse.data); 

       console.log("dsa"+locationId); 
       for (var key in httpResponse.data) { 
        var obj = httpResponse.data[key]; 
        for (var prop in obj) { 
        var eventObj = obj[prop]; 
        if (typeof(eventObj) === 'object' && eventObj.hasOwnProperty("id")) { 
         var FbEvent = Parse.Object.extend("FbEvent"); 
         var fbEvent = new FbEvent(); 
         fbEvent.set("startDate",eventObj["start_time"]); 
         fbEvent.set("locationFbId", locationId); 
         fbEvent.set("fbEventId", eventObj["id"]); 
         fbEvent.set("fbEventName", eventObj["name"]); 

         Parse.Cloud.beforeSave("FbEvent", function(request, response) { 
         var query = new Parse.Query("FbEvent"); 
         query.equalTo("fbEventId", request.params.fbEventId); 
         query.count({ 
          success: function(number) { 
          if(number>0){ 
           response.error("Event not unique"); 
          } else { 
           response.success(); 
          } 
          }, 
          error: function(error) { 
          response.error(error); 
          } 
         }); 
         });     
        } 
        } 
       } 

       completedResults++; 
       if (completedResults == totalResults) { 
        completion(); 
       } 
       }, 
       error:function(httpResponse){ 
       completedResults++; 
       if (completedResults == totalResults) 
        response.error("Failed to login"); 
       } 
      }); 
     } 
     }, 
     error: function() { 
      response.error("Failed on getting locationId"); 
     } 
    }); 
}); 
+0

http://stackoverflow.com/questions/105034/create-guid-uuid-in-javascript 단지 세대 /이 GUID를 사용하여 반환하는 경우에만 저장. –

+0

Srry, 나 didnt는 얻는다. 그리고 나는 내가 나의 질문에서 명백하지 않았다고 생각한다. ID는 페이스 북 API에 의해 주어집니다. 그래서이 ID를 생성하지 않습니다. – adolfosrs

답변

2

이것은 Cloud Code에서 발생합니까? (Im는 자바 스크립트이므로 가정)

"이벤트"개체가 저장되기 전에 발생하는 함수를 만들고 이벤트가 고유한지 확인하기 위해 쿼리를 실행하는 것입니다 ("eventId" 키, objectId가 아닌 Facebook에서 가져온 ID). 지금 조회하여 저장 호출하기 전에

Parse.Cloud.beforeSave("Event", function(request, response) { 
       if(request.object.dirty("eventId")){ 
        var query = var new Parse.Query("Event"); 
        query.equalTo("eventId", request.object.eventId); 
        query.count({ 
         success: function(number) { 
          if(number>0){ 
           response.error("Event not unique"); 
          } else { 
           response.success(); 
          } 
         }, 
         error: function(error) { 
          response.error(error); 
         } 
        }); 
       } else { 
        response.success(); 
       } 
}); 
Parse.Cloud.define("hello", function(request, response) { 
    var query = new Parse.Query("Location"); 
    query.find({ 
     success: function(results) { 
      console.log(results); 
     var totalResults = results.length; 
     var completedResults = 0; 
     var completion = function() { 
      response.success("Finished"); 
     }; 
      for (var i = 0; i < totalResults; ++i){ 
      locationId = results[i].get("locationFbId"); 
      Parse.Cloud.httpRequest({ 
       url: 'https://graph.facebook.com/v2.2/'+locationId+'/events?access_token='+accessToken, 
       success: function(httpResponse) { 
       console.log(httpResponse.data); 
       console.log("dsa"+locationId); 
       for (var key in httpResponse.data) { 
        var obj = httpResponse.data[key]; 
        for (var prop in obj) { 
        var eventObj = obj[prop]; 
        if (typeof(eventObj) === 'object' && eventObj.hasOwnProperty("id")) { 
         var FbEvent = Parse.Object.extend("FbEvent"); 
         var fbEvent = new FbEvent(); 
         fbEvent.set("startDate",eventObj["start_time"]); 
         fbEvent.set("locationFbId", locationId); 
         fbEvent.set("fbEventId", eventObj["id"]); 
         fbEvent.set("fbEventName", eventObj["name"]); 
         // Our beforeSave function is automatically called here when we save it (this will happen every time we save, so we could even upgrade our method as shown in its definition above) 
         fbEvent.save(null, { 
          success: function(event) { 
           console.log('New object created with objectId: ' + event.eventId); 
          }, 
          error: function(event, error) { 
           console.log('Failed to create new object, with error code: ' + error.message); 
          }    
         });     
        } 
        } 
       } 
       completedResults++; 
       if (completedResults == totalResults) { 
        completion(); 
       } 
       }, 
       error:function(httpResponse){ 
       completedResults++; 
       if (completedResults == totalResults) 
        response.error("Failed to login"); 
       } 
      }); 
     } 
     }, 
     error: function() { 
      response.error("Failed on getting locationId"); 
     } 
    }); 
}); 

이도 수행 할 수 있습니다 : 이벤트가 유일하다, 그렇지 않으면 EX는

("없습니다 독특한 이벤트") response.error을 반환 response.success()를 호출 쿼리 숫자 == 0

Summary: For those joining later, what we are doing here is checking to see if an object is unique (this time based on key eventId, but we could use any key) by overriding Parse's beforeSave function. This does mean that when we save our objects (for the first time) we need to be extra sure we have logic to handle the error that the object is not unique. Otherwise this could break the user experience (you should have error handling that doesn't break the user experience anyway though).

+0

예. 이것은 대안입니다. 하지만 좀 더 친숙한 성능을 원했습니다. :/ – adolfosrs

+0

또한. response.success를 반환 한 후 데이터를 저장합니까? 또는 내 event.save를 어느 방향 으로든 호출해야합니까? – adolfosrs

+0

내 Event 객체를 인스턴스화 한 후에 호출합니다. 그리고 이것은 wierd thing "FbEvent에 대한 Error : beforeSave가 이미 등록되었습니다."를 반환합니다. :/어떤 생각? – adolfosrs

관련 문제