Tech

[NJS] Creating a new post

3 min read

Last post in the series is about creating a new post. This wasn't really needed, since the whole point of having my blog in Dropbox was to use any markdown editor I desire, save the file, run the sync command, and have it live, but for the sake of learning, I went ahead and added this feature too.

First, the routes:

router.get("/create/" + process.env.MY_SYNC_KEY, function(req, res) {
  res.render("create-post", {
    title: "Create",
    metadata: "Create a post"
  })
})
 
router.post("/create", function(req, res) {
  if (req.params.token != process.env.MY_SYNC_KEY) { res.redirect("/"); return }
  const body = req.body
Continue reading →

[NJS] Dropbox syncing

14 min read

For Dropbox handling I chose a pretty small library, node-dropbox. To use it, I went in Dropbox's developer dashboard and created an access token (instead of using secrets and keys) and saved that in my .env. Then onto the helper:

const dropbox = require('node-dropbox').api(process.env.ACCESS_TOKEN)
 
function Dropbox() {}
 
Dropbox.getFolder = function(path) {
  return new Promise(function(resolve) {
    // This will get all the metadata for each file from the folder.
    dropbox.getMetadata(path, function(error, result, folder) {
      if (error) {
        console.log('Getting ' + path + ' failed.')
      }
      else {
        resolve(folder)
      }
    })
  })
}
Continue reading →

[NJS] Database handling #3

2 min read

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
}
Continue reading →

[NJS] Database handling #2

10 min read

Last time I was talking about the DbConfig model and the fetchPosts function, so let's dive in. First, a few examples of using the config:

const Db = require('../lib/db')
const DbConfig = require('../models/dbconfig')
 
// Fetching one post
const config = new DbConfig()
config.fields      = ['link']
config.fieldValues = [req.baseUrl.substring(1)] // The path without the initial `/`
config.limit       = 1
Continue reading →

[NJS] Database handling #1

7 min read

With Sinatra, I was using DataMapper as ORM (Object Relational Mapper) for Postgres, and I got a bit spoiled, because it makes things really easy. You first have to define your data mapping:

class Post
  include DataMapper::Resource
  # Set the number of characters for these types of fields, if the DB supports it
  DataMapper::Property::String.length(255)
  DataMapper::Property::Text.length(999999)
  property :id, Serial
  property :title, Text
  property :body, Text
  property :datetime, String
  property :modified, String
  property :link, String
end

And using it is really straightforward:

Continue reading →

[NJS] Layouts

4 min read

Express 2.0 apparently had layouts and partials included, but they were removed in 3.0. Luckily, ejs-mate has us covered.

Let's quickly cover partials, because it feels a bit easier. First, the partial, inside an example.ejs file, located in the same views folder where all your views are kept (preferably inside a nested partials folder):

<p>I am a partial</p>
And I will be included too

Then, when we want this bit of code in another file, we can just include it where it's needed:

<h1>About me</h1>
<% include ./partials/example >
More stuff here

This will be rendered as:

Continue reading →

[NJS] Routing

2 min read

Express offers a really easy routing system, which is the main selling point:

var app = require('express')()
app.use('/', require('./routes/routes'))

This will delegate all routing to the routes.js file, inside the routes folder, at the root level. Here, we delegate individual routes to their specific files, but declaring routes will be just as easy:

var router = require('express').Router()
 
router.use('/privacy-policy', require('./privacy-policy'))
router.use('*', function(req, res) { // req stands for request, res for response
  res.render('not-found') // This is the 404 page, and should be the last route
})
 
module.exports = router
Continue reading →

[NJS] Server, templates and the pipeline

3 min read

As I said in my previous post, I will do a suite of posts regarding the migration of my website from ruby to Node.js, and to make them easier to spot, I will prefix them with [NJS]. Small warning: I'm not a semicolon user. I've read quite a bit about it, and I made my choice knowingly.

So, the first thing I picked was Express, a really nice web application framework. All it takes to have it running is:

var app = require('express')()
 
app.get('/', function(req, res) {
  res.render('index', { name: 'Roland' })
})
app.listen(process.env.PORT || 3000)
app.set('view engine', 'ejs')
Continue reading →

Node.js

25 sec read

Recently I started working on a Node.js project, but since I barely wrote like 50 lines of JS code, ever, I decided to migrate my current ruby based website to a Node.js one, to familiarize with it a bit. In my upcoming posts I will write about how everything goes.

I'm pretty pro null and type safety, so the main thing I'm wondering right now is how I'll feel after writing JS for a while, since it's at the other end of the spectrum compared to Swift: none vs 100% strictness.