Example #1
0
File: client.js Project: imclab/hms
	client.deploy = function(id, opts, cb) {
		if (typeof opts === 'function') return client.deploy(id, null, opts);
		if (!opts) opts = {};

		var req = http.request(xtend(remote, {method:'PUT', path:'/'+id+'?'+qs.stringify(opts)}));

		if (cb) {
			req.on('error', cb);
			cb = once(cb);
		} else {
			cb = noop;
		}

		var done = function(err) {
			if (err) req.emit('error', err);
			cb(err);
		};

		var onbuild = function() {
			req.emit('build');
			req.emit('syncing');
			incref(done, function(p, cb) {
				p.sync(id, null, function(err) {
					if (err) return cb(err);
					req.emit('sync');
					req.emit('restarting');
					p.restart(id, function(err) {
						if (err) return cb(err);
						req.emit('restart');
						req.emit('success');
						cb();
					});
				});
			});
		};

		req.on('response', function(res) {
			if (res.statusCode === 204) {
				res.resume();
				return onbuild();
			}

			if (res.statusCode !== 200) return readError(res, done);

			if (!req.emit('building', res)) res.resume();

			res.on('end', function() {
				var status = parseInt(res.trailers['x-status'] || 200, 10);
				if (status !== 200) return done(new Error('Build failed'));
				onbuild();
			});
		});

		return req;
	};