开发者

Short and unique keys in CouchDB

I want to write a URL shortener as a standalone CouchApp, but I'm wondering if it is possible. Obviously, a core requirement for a URL shortener is to have short and unique keys.

What I want is to POST a long URL to CouchDB and get a shortened URL. I thought about using an update handler, but it would have to query the DB to check if the key is unique, which seems not to be possib开发者_如何学JAVAle.

Is there a way to generate short and unique keys with CouchDB? Or do I need a thin wrapper around CouchDB?


I would go for a thin wrapper, based on documents with the following structure:

{ _id : short_url , url : long_url }

Inserting of a new long URL could be done in a single step: have the wrapper generate a new _id, attempt a PUT, and try again with a new _id until it succeeds. This will guarantee that every short URL is only used once.

I'm afraid this "generate, attempt, retry" approach is the only strategy that ensures uniqueness, and it's not available without a wrapper.

If you wish the same long URL to reuse the same short URL, you can also add a view that echo(doc.url,null) and grab the _id for your URL if it does exist. This means that, unless several clients try to add the same long URL at the exact same time, only one short URL will be used for that long URL.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜