未加星标

Creating Documents in DocumentDB with Azure Functions HTTP API

字体大小 | |
[数据库(综合) 所属分类 数据库(综合) | 发布者 店小二03 | 时间 2017 | 作者 红领巾 ] 0人收藏点击收藏

Thus far in my story of implementing Azure Mobile Apps in a dynamic (consumption) plan of Azure Functions using DocumentDB , I’ve got the basic CRUD HTTP API stubbed out and the initialization of my DocumentDB collection done. It’s now time to work on the actual endpoints that my Azure Mobile Apps SDK will call. There are five methods to implement:

Insert Update / Replace Delete Fetch a single record Search

I’m going to do these in the order above. Before I do that, I need to take a look at what DocumentDB provides me. Azure Mobile Apps requires five fields to work properly:

id a string (generally a GUID). createdAt the date the record was created, in ISO-8601 format. updatedAt the date the record was updated, in ISO-8601 format. deleted a boolean, if the record is deleted. version an opaque string for conflict resolution.

DocumentDB provides some of this for us:

id a string (generally a GUID). _ts a POSIX / unix timestamp of the number of seconds since the epoch since the record was last updated. _etag a checksum / version identifier.

When we create a record, we need to convert the document that DocumentDB returns to us into the format that Azure Mobile Apps provides. I use the following routine:

/**
* Given an item from DocumentDB, convert it into something that the service can used
* @param {object} item the original item
* @return {object} the new item
*/
function convertItem(item) {
if (item.hasOwnProperty('_ts')) {
item.updatedAt = moment.unix(item._ts).toISOString();
delete item._ts;
} else {
throw new Error('Invalid item - no _ts field');
}
if (item.hasOwnProperty('_etag')) {
item.version = new Buffer(item._etag).toString('base64');
delete item._etag;
} else {
throw new Error('Invalid item - no _etag field');
}
// Delete all the known fields from documentdb
if (item.hasOwnProperty('_rid')) delete item._rid;
if (item.hasOwnProperty('_self')) delete item._self;
if (item.hasOwnProperty('_attachments')) delete item._attachments;
return item;
}

I’m using the moment library to do date/time manipulation. This is a very solid library and well worth learning about. In addition to the convertItem() method, I also need something to convert the error values that come back from DocumentDB. They are not nicely formed, so some massaging is in order:

/**
* Convert a DocumentDB error into something intelligible
* @param {Error} error the error object
* @return {object} the intelligible error object
*/
function convertError(error) {
var body = JSON.parse(error.body);
if (body.hasOwnProperty("message")) {
var msg = body.message.replace(/^Message:\s+/, '').split(/\r\n/);
body.errors = JSON.parse(msg[0]).Errors;
var addl = msg[1].split(/,\s*/);
addl.forEach((t) => {var tt = t.split(/:\s*/);tt[0] = tt[0].replace(/\s/, '').toLowerCase();body[tt[0]] = tt[1];
});
delete body.message;
}
return body;
}

I had to work through the error object several times experimenting with the actual response to come up with this routine. This seems like the right code by experimentation. Whether it holds up during normal usage remains to be seen.

I’ve already written the createDocument() method in the DocumentDB driver:

module.exports = {
createDocument: function (client, collectionRef, docObject, callback) {
client.createDocument(collectionRef._self, docObject, callback);
}
};

This is then promisifyed using the bluebird promise library . With this work done, my code for inserts becomes very simple:

function insertItem(req, res) {
var item = req.body;
item.createdAt = moment().toISOString();
if (!item.hasOwnProperty('deleted')) item.deleted = false;
driver.createDocument(refs.client, refs.table, item)
.then((document) => {
res.status(201).json(convertItem(document));
})
.catch((error) => {
res.status(error.code).json(convertError(error));
});
}

The item that we need to insert comes in on the body. We need to add the createdAt field and the deleted field (if it isn’t already set). Since this is an insert, we call createDocument() in the driver. If it succeeds, we return a 201 Created response with the new document (converted to the Azure Mobile Apps specification). If not, we return the error from DocumentDB together with the formatted object.

We can test inserts with Postman. For example, here is a successful insert:


Creating Documents in DocumentDB with Azure Functions HTTP API

DocumentDB creates the id for me if it doesn’t exist. I convert the _ts and _etag fields to something more usable by the Azure Mobile Apps SDK on the way back to the client. If I copy the created object and push it again, I will get a conflict:


Creating Documents in DocumentDB with Azure Functions HTTP API

Notice how DocumentDB does all the work for me? All I need to do is some adjustments on the output to get my insert operation working. I can use the Document Browser within the Azure Portal to look at the actual records.

In the next post, I’m going to move onto Update, Delete and Fetch all in one go.

本文数据库(综合)相关术语:系统安全软件

分页:12
转载请注明
本文标题:Creating Documents in DocumentDB with Azure Functions HTTP API
本站链接:http://www.codesec.net/view/529805.html
分享请点击:


1.凡CodeSecTeam转载的文章,均出自其它媒体或其他官网介绍,目的在于传递更多的信息,并不代表本站赞同其观点和其真实性负责;
2.转载的文章仅代表原创作者观点,与本站无关。其原创性以及文中陈述文字和内容未经本站证实,本站对该文以及其中全部或者部分内容、文字的真实性、完整性、及时性,不作出任何保证或承若;
3.如本站转载稿涉及版权等问题,请作者及时联系本站,我们会及时处理。
登录后可拥有收藏文章、关注作者等权限...
技术大类 技术大类 | 数据库(综合) | 评论(0) | 阅读(87)