12 May 2014, 17:46
Generic-user-small

liu huyu (2 posts)

  /**
   * put a book into a bundle by its id
   * curl -X PUT http://localhost:3000/api/bundle/<id>/book/<pgid>
   */
  app.put('/api/bundle/:id/book/:pgid', function(req, res) {

    Q.async(function * () {

      let
      args = yield Q.nfcall(request.get, config.b4db + req.params.id),
      couchRes = args[0],
      bundle = JSON.parse(args[1]);

      // fail fast if we couldn't retrieve the bundle
      if (couchRes.statusCode !== 200) {
        res.json(couchRes.statusCode, bundle);
        return;
      }

      // look up the book by its Project Gutenberg ID
      args = yield Q.nfcall(request.get, config.bookdb + req.params.pgid);
      couchRes = args[0];
      book = JSON.parse(args[1]);

      // fail fast if we couldn't retrieve the book
      if (couchRes.statusCode !== 200) {
        res.json(couchRes.statusCode, book);
        return;
      }

      // add the book to the bundle
      bundle.books[book._id] = book.title;

      // put the updated bundle back into CouchDB
      request.put({
        url: config.b4db + bundle._id,
        json: bundle
      }).pipe(res);

    })()
      .
    catch (function(err) {
      res.json(502, {
        error: "bad_gateway",
        reason: err.code
      });
    });
  });

like the way remove a book from a bundle

/**
   * remove a book from a bundle
   * curl -X DELETE http://localhost:3000/api/bundle/<id>/book/<pgid>
   */
  app.del('/api/bundle/:id/book/:pgid', function(req, res) {
    Q.async(function * () {

      let
      args = yield Q.nfcall(request, config.b4db + req.params.id),
      couchRes = args[0],
      bundle = JSON.parse(args[1]);

      // fail fast if we couldn't retrieve the bundle
      if (couchRes.statusCode !== 200) {
        res.json(couchRes.statusCode, bundle);
        return;
      }

      // fail if the bundle doesn't already have that book
      if (!(req.params.pgid in bundle.books)) {
        res.json(409, {
          error: "conflict",
          reason: "Bundle does not contain that book."
        });
        return;
      }

      // remove the book from the bundle
      delete bundle.books[req.params.pgid];

      // put the updated bundle back into CouchDB
      request.put({
        url: config.b4db + bundle._id,
        json: bundle
      }).pipe(res);

    })()
      .
    catch (function(err) {
      res.json(502, {
        error: "bad_gateway",
        reason: err.code
      });
    });
  });
12 May 2014, 17:49
Generic-user-small

liu huyu (2 posts)

it rep a bad_gateway error the focus is put used two Q.nfcall and del use one

  You must be logged in to comment