SoftDelete implementation with JayData

by JayData

HTML

<script src="http://include.jaydata.org/jaydata.min.js"></script>

JavaScript

$data.Entity.extend("Category", {
    Id: { key: true, type: "int", computed: true },
    Name: { type: "string", required: true },
    Products: { type: Array, elementType: "Product", inverseProperty: "Category" },
    IsDeleted: { type: "bool" }
});

//Define the Product entity with the Category reference
$data.Entity.extend("Product", {
    Id: { key: true, type: "int", computed: true },
    Name: { type: "string", required: true },
    Category: { type: "Category", inverseProperty: "Products" }
});

//Define our context with typed EntitySets (tables), which will provide access to our database
$data.EntityContext.extend("NorthwindContext", {
    Categories: { type: $data.EntitySet, elementType: Category, isSoftDelete: true },
    Products: { type: $data.EntitySet, elementType: Product }
});

//SoftDelete
$data.EntitySet.addMember('physicalRemove', $data.EntitySet.prototype.remove);
$data.EntitySet.addMember('remove', function(item){
    if(this.entityContext.getType().getMemberDefinition(this.collectionName).isSoftDelete){
        this.attach(item)
        item.IsDeleted = true;
    }else{
        this.physicalRemove.apply(this, arguments);
    }
});


//Initialize a WebSQL/SQLite database connection with the defined schema
var nw = new NorthwindContext({ provider: "webSql", databaseName: "northwind2" });

nw.onReady(function () {
    var newDep = new Category({ Name: 'Food7' });
    nw.Categories.add(newDep);
    nw.saveChanges(function () {
        console.log('New category has been changed');
        //nw.Categories.remove(newDep);
        //nw.saveChanges(function(){
        newDep.remove().then(function(){
            nw.Categories.toArray($data.debug);
        });
    });
});