[Swift] Bitwise masking, p.3

Previous parts are descriptive, in this part I’m considering described approach on practice, within server-side communication, in case of MongoDB, Node.js and added Mongoose dependency to it.

Here is simple mongoose schema:
in real development, use ObjectId, instead of raw data types, like in “ingredients” and “category”

// Node.js
// Recipe
{
name: String,
ingredients: [Number],
category: Number
}

In mongo shell, I have set next documents:

> db.recipes.insert({ name: ‘Caesar salad’, ingredients: [1, 7, 8]})
> db.recipes.insert({ name: ‘Coffee’, ingredients: [0, 2] })
> db.recipes.insert({ name: ‘Milk cocktail’, ingredients: [3, 8] })

What if you need to get all recipes, which is have one or more of selected ingredient? Just send integer encoded in binary format to server.

// Swift
...
let binaryValue = 132 // generated binary value by BitwiseSwitcher
let request = NSURLRequest(URL: NSURL(string: "http://localhost:8080/api/recipes/ingredient/list/\(binaryValue)")!)
NSURLSession.sharedSession().dataTaskWithRequest(request) { 
let res = try? NSJSONSerialization.JSONObjectWithData($0.0!, options: [])
print("\(res)")
}.resume()

On server-side, router catches declared query structure and execute function, with filtering of recipes:

// Node.js
// Route
...
app.get('/api/recipes/ingredient/list/:ingredients', function(req, res) {
const ingredientsArr = [];

const binaryValue = parseInt(req.params.ingredients).toString(2);
binaryValue.split('').map(function(el) { return parseInt(el) })
.reverse()
.forEach(function(el, index) {
if(el == 1) ingredientsArr.push(index)
});

Recipe.find({ ingredients: { $in: ingredientsArr }}, function(err, list) {
res.json(list);
})
});

In result, response has filtered data, on the stated requirements, where recipes have declared ingredients encoded in binary value: 132, which is: [2, 7].
Recipes names: Caesar salad and Coffee.


This technique of value storing is very powerful if use it properly!

Like what you read? Give Dima Pilipenko a round of applause.

From a quick cheer to a standing ovation, clap to show how much you enjoyed this story.