你希望它在这里

2026年8月27日1 次浏览来源:Dev.to阅读原文

正文保留英文原文(机翻易破坏代码与排版),标题/摘要已提供中文

I know how tough it can be to build smooth, secure backend features, so I wanted to bring a little joy to your day and give something back to this amazing community.

Consider this fully polished, production-ready gift redemption system my happy little present to you!

Inside, you will find clean logic and a complete Node.js/MongoDB transaction example that you can unwrap, drop right into your projects, and use to surprise your own users.

The Logic:

1.

Security & Validation Authentication: The code checks if the user is logged in using the middleware.

ID Validation: It ensures the gift ID in the URL is a valid database ID.

2.

Character Limit Math The maximum character limit allowed is 4000 characters.

It calculates how close the user currently is to that limit.

It attempts to grant the user a +100 character boost, capping it if they are already near the 4000-character threshold (think of it like a partial gift).

Concurrency Handling: While the system may calculate the same value for concurrent requests, MongoDB's atomic operation ensures that if applying both boosts exceeds the 4000-character limit, only the faster request succeeds

3.

Database Transaction (All or Nothing) The system utilizes a database transaction.

This ensures that both the gift update and the user update must succeed together; otherwise, the entire operation rolls back.

Updating the Gift: The query looks for an active gift that this specific user has not claimed yet.

It increments the gift's usage count (), logs the user's ID in the array so they cannot claim it again, and changes the status to "expired" if it just reached its maximum available uses.

Updating the User: It adds the calculated character boost to the user's account.

If the gift is invalid, fully depleted, or already claimed by the logged-in user, the code throws an error and aborts the entire transaction.

Otherwise, it successfully returns a response.

The Code: Note: A block is unnecessary here because I am using the package.

All asynchronous errors are automatically caught and forwarded to the global error-handling middleware.

If you want to view the entire system, check https://github.com/Hfs2024/Vlox.

Hope you liked your 🎁!

分享