How to use restify

Comprehensive restify code examples:

How to use restify.gzipResponse:

74
75
76
77
78
79
80
81
82
83
if ( nconf.get('Security:UseACL') ) {
  plugins.push( require( path.join(__dirname, 'plugins', 'customACLPlugin') )() );
}

plugins.push( restify.bodyParser() );
plugins.push( restify.gzipResponse() );

server.use( plugins );

/**

How to use restify.acceptParser:

58
59
60
61
62
63
64
65
66
67
68
  ip: false,
  username: true
};


var plugins = [
  restify.acceptParser(server.acceptable),
  restify.throttle(throttleOptions),
  restify.dateParser(),
  restify.queryParser(),
  restify.fullResponse()

How to use restify.fullResponse:

62
63
64
65
66
67
68
69
70
71
72
var plugins = [
  restify.acceptParser(server.acceptable),
  restify.throttle(throttleOptions),
  restify.dateParser(),
  restify.queryParser(),
  restify.fullResponse()
];


if (nconf.get('Security:UseAuth')) {
  plugins.push(require(path.join(__dirname, 'plugins', 'customAuthorizationParser'))());

How to use restify.dateParser:

60
61
62
63
64
65
66
67
68
69
70
};


var plugins = [
  restify.acceptParser(server.acceptable),
  restify.throttle(throttleOptions),
  restify.dateParser(),
  restify.queryParser(),
  restify.fullResponse()
];

How to use restify.InvalidHeaderError:

15
16
17
18
19
20
21
22
23
if (!auth || !Object.keys(auth).length) {
  return callback(new restify.UnauthorizedError('An API key is required for this endpoint.'));
}

if (auth.scheme !== 'deconst') {
  return callback(new restify.InvalidHeaderError('Your Authorization header specifies an incorrect scheme.'));
}

var match = credentialRx.exec(auth.credentials);

How to use restify.BadMethodError:

35
36
37
38
39
40
41
42
43
44

    return error;
}

function BadMethodError(msg , outMsg){
    var error = new restify.BadMethodError(msg);
    if(outMsg){
        error.body.outMsg = outMsg;
    }
    return error;

How to use restify.ForbiddenError:

66
67
68
69
70
71
72
73
74
75
*  verror.WError
*    restify.HttpError
*      restify.RestError
*
*        # The subset of core restify errors that are used.
*        restify.ForbiddenError
*        restify.ResourceNotFoundError
*        ...
*
*        # Customized restify core errors.

How to use restify.NotFoundError:

53
54
55
56
57
58
59
60
61
62

employeeService.getPicture(req.user.email, employeeId, pictureType)
    .then(picture => {

        if (!picture || picture === '' || picture === null) {
            res.send(new restify.NotFoundError());
            next();
        } else {
            res.writeHead(200, { 'Content-Type': 'image/jpeg' });
            res.end(picture);

How to use restify.UnprocessableEntityError:

37
38
39
40
41
42
43
44
45
46
    if (err.fatal) {
        return new restify.ServiceUnavailableError('Database Fatal Error: ' + err.code);
    } else if (err.code === 'ER_DUP_ENTRY') {
        return new restify.BadRequestError('Request can not accomplished, cause of duplicate entrys in the database');
    }
    return new restify.UnprocessableEntityError('Database query failed: ' + err.code);
};

function getPool() {
    return this.pool;

How to use restify.throttle:

59
60
61
62
63
64
65
66
67
68
69
  username: true
};


var plugins = [
  restify.acceptParser(server.acceptable),
  restify.throttle(throttleOptions),
  restify.dateParser(),
  restify.queryParser(),
  restify.fullResponse()
];

How to use restify.InvalidCredentialsError:

20
21
22
23
24
25
26
27
28
29
if(!data.organization || !data.organization.id) {
  return next(new restify.InvalidCredentialsError('Bad Request: missing organization id'));
}

if(!data.user || !data.user.id) {
  return next(new restify.InvalidCredentialsError('Bad Request: missing user id'));
}

if(!data.hash) {
  return next(new restify.InvalidCredentialsError('Bad Request: missing hash'));

How to use restify.InternalServerError:

77
78
79
80
81
82
83
84
85
86

router.post('/user', (req, res) => {
  if (!req.params.username || !req.params.password || !req.params.email) return res.send(new restify.BadRequestError('Missing username and/or password and/or email'));

  bcrypt.hash(req.params.password, 8, async (err, hash) => {
    if (err) return res.send(new restify.InternalServerError('Internal server error'));

    const existing = await User.findOne({
      where: {
        $or: [

How to use restify.createStringClient:

52
53
54
55
56
57
58
59
60
61
case 'https' : case 'http' :
  client = restify.createClient(options.client || {});
break;

case 'string' :
  client = restify.createStringClient(options.client || {});
break;

case 'socket' :
  // to do

How to use restify.createClient:

48
49
50
51
52
53
54
55
56
57
  client = restify.createJsonClient(options.client || {});
break;


case 'https' : case 'http' :
  client = restify.createClient(options.client || {});
break;

case 'string' :
  client = restify.createStringClient(options.client || {});

How to use restify.HttpError:

62
63
64
65
66
67
68
69
70
71
*
*
* Error Hierarchy:
*
*  verror.WError
*    restify.HttpError
*      restify.RestError
*
*        # The subset of core restify errors that are used.
*        restify.ForbiddenError

How to use restify.bodyParser:

146
147
148
149
150
151
152
153
154
155

// POST '/:apiversion/networks/create'
http.post({ path: /^(\/v[^\/]+)?\/networks\/create$/,
    name: 'NetworkCreate' },
    before,
    restify.bodyParser(),
    queryParser,
    networkCreate);

// DELETE '/:apiversion/networks/:id'

How to use restify.queryParser:

136
137
138
139
140
141
142
143
144
145
    mapParams: false,
    // See: https://smartos.org/bugview/ZAPI-744
    allowDots: false,
    plainObjects: false
};
var queryParser = restify.queryParser(queryParserOpts);

// GET '/:apiversion/networks'
http.get({ path: /^(\/v[^\/]+)?\/networks$/, name: 'NetworkList' },
    before, queryParser, networkList);

How to use restify.MethodNotAllowedError:

21
22
23
24
25
26
27
28
29
30
31
32
33
const ALLOWED_APP_EXTENSIONS = [".zip", ".fma"];


const GCODE_EXTENSIONS = [".nc", ".g", ".gc", ".gcode"];
const OPENSBP_EXTENSIONS = [".sbp", ".sbc"];


var MethodNotAllowedError = errors.MethodNotAllowedError;
var NotAuthorizedError = errors.NotAuthorizedError;
var ResourceNotFoundError = errors.ResourceNotFoundError;


function listify(x) {

How to use restify.ConflictError:

258
259
260
261
262
263
264
265
266
267
});

if (workflow.chain) {
    workflow.chain.forEach(function (task, i, arr) {
        if (!task.body) {
            error = new restify.ConflictError('Task body is required');
        }
        task.body = vm.runInNewContext('(' + task.body + ')', {});
        if (task.fallback) {
            task.fallback =

How to use restify.BadRequestError:

36
37
38
39
40
41
42
43
44
let employeeId = req.params.employeeId;

let pictureType = req.query.pictureType || '1';

if (!employeeId) {
    res.send(new restify.BadRequestError('Invalid employee id'));
    next();
    return;
}

How to use restify.ServiceUnavailableError:

168
169
170
171
172
173
174
175
176
177

// Return Service Unavailable if backend is not connected
server.use(function ensureBackendConnected(req, res, next) {
    if (typeof (backend.connected) !== 'undefined' &&
        backend.connected === false) {
        return next(new restify.ServiceUnavailableError(
            'Backend not connected'));
    }

    return next();

How to use restify.UnauthorizedError:

44
45
46
47
48
49
50
51
52
}

return employeeQueryService.getEmployeeByUserName(req.user.email).then(function (employee) {

    if (employeeId === employee.id) {
        res.send(new restify.UnauthorizedError());
        next();
        return;
    }

How to use restify.NotAuthorizedError:

46
47
48
49
50
51
52
53
54
55
        return next();
    } else {
        res.status(401);
        res.setHeader('Connection', 'close');
        res.end();
        return next(new Restify.NotAuthorizedError());
    }
} else {
    return next();
}

How to use restify.RestError:

99
100
101
102
103
104
105
106
107
108

// ---- globals

var p = console.warn;
var fmt = util.format;
var RestError = restify.RestError;



// ---- exported functions

How to use restify.CORS:

21
22
23
24
25
26
27
28
29
30
  });
  next();
});
server.use(restify.authorizationParser());
server.use(restify.fullResponse());
restify.CORS.ALLOW_HEADERS.push('authorization'); //the restify CORS headers don't come with authorization
server.use(restify.CORS());
server.use(validate.validationPlugin({ errorsAsArray: false })); //inline route validation support

server.get('/', function(req, res) {

How to use restify.MissingParameterError:

20
21
22
23
24
25
26
27
28
29
var operation = req.app.sockets.getSocket('job', id);

if (!id || !operation) {
    return next(new restify.ResourceNotFoundError('Operation not found'));
} else if (!payload) {
    return next(new restify.MissingParameterError('Missing payload'));
}

operation.socket.write(JSON.stringify(payload));
res.send(200);

How to use restify.bunyan:

29
30
31
32
33
34
35
36
37
38
if (!opts.logger) {
    opts.logger = {};
}

opts.logger.name = 'workflow-api';
opts.logger.serializers = restify.bunyan.serializers;

opts.logger.streams = opts.logger.streams || [ {
    level: 'info',
    stream: process.stdout

How to use restify.errors:

147
148
149
150
151
152
153
154
155
156

// update note
note.save({data: params.data, hash: params.hash, updateTime: time}, function ( error ) {
    if ( error ) {
        debug(error);
        return callback(new restify.errors.InternalServerError('data saving failure'));
    }

    callback(null, true);
});

How to use restify.InternalError:

227
228
229
230
231
232
233
234
235
236
backend.getWorkflows(req.params, function (err, workflows) {
    if (err) {
        if (err.toRestError) {
            return next(err.toRestError);
        } else {
            return next(new restify.InternalError(err));
        }
    }
    res.send(200, workflows);
    return next();