Skip to content

Instantly share code, notes, and snippets.

@pmoelgaard
Created October 26, 2015 18:34
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save pmoelgaard/bf1091d5827e85d5a27f to your computer and use it in GitHub Desktop.
Save pmoelgaard/bf1091d5827e85d5a27f to your computer and use it in GitHub Desktop.
Random MySQL Mixin for Loopback
/// <reference path='../../typings/tsd.d.ts' />
/// <reference path='../../local_modules/tsd.d.ts' />
import path = require('path');
import async = require('async');
import _ = require('lodash');
import IRemoteMethodCallbackFunction = loopback.IRemoteMethodCallbackFunction;
import IMySQLTableDefinition = loopback.IMySQLTableDefinition;
import IPersistenceModelItem = loopback.IPersistenceModelItem;
function Mixin(Model:loopback.IPersistenceModel):void {
Model['random'] = function (callback:IRemoteMethodCallbackFunction):void {
async.waterfall([
function (stepCallback:Function):void {
switch (Model.dataSource.connector.name) {
case 'mysql':
var tableDefinition:IMySQLTableDefinition = <IMySQLTableDefinition>Model.definition.settings['mysql'];
var query:string = 'SELECT T.id FROM `' + tableDefinition.table + '` T ORDER BY RAND() LIMIT 1';
Model.dataSource.connector.query(query, function (err:Error, result:Array<any>):void {
if (err) {
return stepCallback(err);
}
if (result.length > 0) {
result = result.pop();
}
var value:string|number = _.get(result, 'id');
stepCallback(null, value);
})
break
default:
return callback({'Only MySQL connectors are supported at the moment.'})
break;
}
}
,
function (id:string|number, stepCallback:Function):void {
Model.findById(id, function (err:Error, result:IPersistenceModelItem):void {
stepCallback(err, result);
})
}
],
function (err:Error, result:IPersistenceModelItem):void {
callback(err, result);
}
)
}
Model.remoteMethod(
'random',
{
accepts: [],
returns: {arg: 'document', type: 'object', root: true},
http: {path: '/random', verb: 'get'}
}
)
}
export = Mixin;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment