---
title: "[NJS] Database handling #3"
slug: njs-database-handling-3
section: tech
date: 2016-08-22T21:32:00.000Z
canonical: https://roland.leth.ro/blog/tech/njs-database-handling-3
---

[Last time](/tech/blog/database-handling-2) 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:

```js
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:

```js
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:

```js
// 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.
