Can someone please explain what’s the use of this pattern with example?
All I’m confused is that I can have database instance wherever I want and I have flexibility to do anything by it, am I wrong? specially is
Advertisement
Answer
The repository pattern is a strategy for abstracting data access.
it’s like putting a universal adapter in between your application and your data so it doesn’t matter what data storage technology you use. All your app wants is having defined operations on items, it shouldn’t have to care about how it’s stored or where it comes from.
Also, there’s no need to mention that all impacts of changes will be handled from one place instead of cascading all through your code!
Personally, I love this design pattern because it allows me to only have concerns about my business logics at the first steps instead of dealing with variant databases, on top of that, it solves a huge amount of my headaches when it comes to writing tests! So instead of stubbing or spying databases, which can be a headache, I can simply enjoy a mock version of operations
Now let’s implement a sample in js, it can be just as simple as below code (it’s a simplified sample of course)
// userRepository.js const userDb = []; module.exports = { insert: async (user) => userDb.push(user), findAll: async () => userDb, };
here is how I use this pattern, first I write something like below code in a 5 minute
// userRepository.js const userDb = new Map(); module.exports = Object.freeze({ findById: async (id) => userDb.get(id), insert: async (user) => userDb.set(user.id, user), findAll: async () => Array.from(userDb.values()), removeById: async (id) => userDb.delete(id), update: async (updatedUser) => { if (!userDb.has(updatedUser.id)) throw new Error('user not found'); userDb.set(updatedUser.id, { ...userDb.get(updatedUser.id), ...updatedUser }); }, });
Then I start to write my unit tests for repository that I’ve just written and business use-cases and so on…
anytime I’m satisfied with everything I can simply use a real database, because it’s just an IO mechanism, isn’t it? 🙂 So in above code I’ll replace userDb with a real database and write real data access methods, and of course expect all my tests to be passed.