Last active
August 29, 2015 13:57
-
-
Save rolaveric/9410549 to your computer and use it in GitHub Desktop.
Example of an existing legacy Javascript object we want to port to Go.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// User Type | |
function User(name, id) { | |
this.name = name; | |
this.id = id; | |
this.save = function () { | |
DB.query('UPDATE User SET name = ? WHERE id = ?', this.name, this.id); | |
} | |
} | |
// Factory for creating a new user | |
User.new = function (name) { | |
DB.query('INSERT INTO User (name) VALUES (?)', name); | |
var id = DB.query('SELECT @@IDENTITY').nextRow()[0]; | |
return new User(name, id); | |
}; | |
// Retrieves a user from the database | |
User.get = function (id) { | |
var result = DB.query('SELECT name FROM User WHERE id = ?', id); | |
if (result.rowCount === 0) { | |
return null; | |
} | |
var name = result.nextRow()[0]; | |
return new User(name, id); | |
}; | |
// Retrieves all users from the database | |
User.all = function () { | |
var users = []; | |
var result = DB.query('SELECT name, id FROM User'); | |
for (var x = 0; x < result.rowCount; x++) { | |
var row = result.nextRow(); | |
users.push(new User(row[0], row[1])); | |
} | |
return users; | |
}; | |
// Use case that still needs to use this model | |
function myHttpHandler(request) { | |
if (request.method === 'GET') { | |
var id = request.params['userid']; | |
if (id) { | |
return User.get(id); | |
} else { | |
return User.all(); | |
} | |
} else if (request.method === 'POST') { | |
return User.new(request.params['name']); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment