CouchDB 中的短键和唯一键
我想编写一个 URL 缩短器作为独立的 CouchApp,但我想知道是否可能。 显然,URL 缩短器的核心要求是拥有简短且唯一的密钥。
我想要的是将一个长 URL POST 到 CouchDB 并获得一个缩短的 URL。我考虑过使用更新处理程序,但它必须查询数据库来检查密钥是否唯一,这似乎不可能。
有没有办法使用 CouchDB 生成简短且唯一的密钥?或者我需要对 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 possible.
Is there a way to generate short and unique keys with CouchDB? Or do I need a thin wrapper around CouchDB?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我会选择一个基于具有以下结构的文档的薄包装器:
插入新的长 URL 可以一步完成:让包装器生成新的
_id
,尝试 PUT,然后使用新的_id
重试,直到成功。这将保证每个短 URL 只使用一次。恐怕这种“生成、尝试、重试”方法是确保唯一性的唯一策略,并且没有包装器就无法使用。
如果您希望相同的长 URL 重用相同的短 URL,您还可以添加一个
echo(doc.url,null)
的视图,并获取 URL 的_id
(如果存在)。这意味着,除非多个客户端尝试同时添加相同的长 URL,否则该长 URL 将仅使用一个短 URL。I would go for a thin wrapper, based on documents with the following structure:
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.