Skip to content

Instantly share code, notes, and snippets.

@tj
Last active January 3, 2016 15:49
Show Gist options
  • Star 18 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
  • Save tj/8485653 to your computer and use it in GitHub Desktop.
Save tj/8485653 to your computer and use it in GitHub Desktop.
/**
* POST to create a new user.
*/
exports.create = function *(){
var body = yield parse(this);
// password
var pass = body.password;
assert(pass, 400, 'password is required');
delete body.password;
let {salt, hash} = yield password(pass);
body.password_salt = salt;
body.password_hash = hash;
// validate
users.schema.validate(body);
// see if the user exists
var exists = yield users.findOne({ username: body.username }, 'name');
assert(!exists, 400, 'username is taken');
// save
yield users.insert(body);
this.status = 201;
};
@tj
Copy link
Author

tj commented Jan 18, 2014

this could of course be moved to a lib and you could do yield db.users.create(body);

  var creds = auth(this);
  assert(creds, 400, 'credentials required');

  var user = yield db.users.findOne({ username: creds.name });
  var hash = yield password(creds.pass, user.password_salt);
  assert(hash == user.password_hash, 401);

<3

@Acconut
Copy link

Acconut commented Jan 18, 2014

I think I should learn to use generators... <3

@polotek
Copy link

polotek commented Jan 18, 2014

Does this pattern have any solution for managing multiple calls in parallel. E.g. the equivalent of Q.all with promises?

@Swatinem
Copy link

That would just be yield [a, b, c] in co i quess.

@jeffmo
Copy link

jeffmo commented Jan 19, 2014

What would idiomatic client code using this generator look like?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment