Last time we created a basic database handling functionality, but it was clear we can improve it: posts aren't the only ones that need fetching, and requiring the dbconfig
file everywhere (and configuring the object) will become cumbersome. So, a first step would be to create specialized DbConfig
objects:
DbConfig.page = function(page) {
const config = new DbConfig()
config.offset = config.limit * (page - 1)
return config
}
DbConfig.post = function(link) {
const config = new DbConfig()
config.fields = ['link']
config.fieldValues = [link]
config.limit = 1
return config
}
// And so on, for archive, sitemap, search and feed and update
Then, the next and final step would be to create Db
helper methods. For example, fetching one post would go from this:
const DbConfig = require('../models/dbconfig')
const config = DbConfig.post
config.fields = ['link']
config.fieldValues = [url]
config.limit = 1
Db.fetchPosts(config).then(function(data) {
// do stuff
})
To this:
// Inside db.js
Db.fetchPost = function(link) {
return Db.fetchPosts(DbConfig.post(link))
}
// Somewhere where a post is needed
Db.fetchPost(url).then(function(data) {
// do stuff
})
Each fetch
method is currently used only once, and all this might not seem much, but dbconfig
is now required
only inside db
, and all variations of DbConfig
are easily found in one place. Also, if one of the fetch
methods will be used somewhere else, no code will be duplicated.