How to use restify - 10 common examples

To help you get started, we’ve selected a few restify examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github adamfowleruk / mljs / test / alerts / 001-create-alert.js View on Github external
client.websocket.sendUTF(JSON.stringify({response: "alert", content: req.body.toString()})); // TESTED - WORKS A TREAT! - TODO check this works fine for XML too
      // TODO do we want to send a multipart that describes the data???
    }*/

    logger.debug("RECEIVED ALERT!");

    res.send("OK");

    done();

    self.close();

  };

  this.server = restify.createServer({name: "MLJSAlertServer"});
  this.server.use(restify.bodyParser()); // { mapParams: false }

  // Server request 1: handle echo directly to client
  //server.get('/echo/:clientid', respond);
  //server.head('/echo/:clientid', respond);
  this.server.post('/alert/:clientid', respond);

  var self = this;
  this.server.listen(this.port, function() {
    logger.debug((new Date()) + ' - MLJS Alert Receiving HTTP Server listening at %s', self.server.url);
  });

  logger.debug("Created alert server");
};
github cmawhorter / hmmac / test / api / server.js View on Github external
var restify = require('restify');

var server = restify.createServer();
server.pre(restify.pre.pause());

// timeout requests
server.use(function(req, res, next) {
  next();

  res.timeoutFn = setTimeout(function() {
    if (!res.finished) res.end();
  }, 30000);
});

// we're done. clear timeout.
server.on('after', function(req, res, route, err) {
  if (res.timeoutFn) clearTimeout(res.timeoutFn);
});

server.use(restify.acceptParser(server.acceptable));
github acarl / pg-restify / test / helper.js View on Github external
server.on('uncaughtException', function(req, res, route, err) {
    if (res._headerSent) {
      // If this response was already sent this could be any error.
      // Because domains are weird you could actually have test case
      // validation errors enter this method.
      // If this happens just throw the err.
      throw err;
    }
    log.error(err);
    res.send(new restify.InternalError('Internal error'));
  });
github kwhitley / apicache / test / api / restify-gzip.js View on Github external
function MockAPI(expiration, options, toggle) {
  var apicache = require('../../src/apicache').newInstance(options)
  var app = restify.createServer()

  // ENABLE COMPRESSION
  var whichGzip = restify.gzipResponse && restify.gzipResponse() || restify.plugins.gzipResponse()
  app.use(whichGzip)

  // EMBED UPSTREAM RESPONSE PARAM
  app.use(function(req, res, next) {
    res.id = 123
    next()
  })

  // ENABLE APICACHE
  app.use(apicache.middleware(expiration, toggle))
  app.apicache = apicache

  app.use(function(req, res, next) {
    res.charSet('utf-8')
    next()
  })
github cmawhorter / hmmac / test / api / server.js View on Github external
// timeout requests
server.use(function(req, res, next) {
  next();

  res.timeoutFn = setTimeout(function() {
    if (!res.finished) res.end();
  }, 30000);
});

// we're done. clear timeout.
server.on('after', function(req, res, route, err) {
  if (res.timeoutFn) clearTimeout(res.timeoutFn);
});

server.use(restify.acceptParser(server.acceptable));
server.use(restify.dateParser());
server.use(restify.jsonp());
server.use(restify.gzipResponse());
server.use(restify.bodyParser({ mapParams: false }));

module.exports = server;
github ritazh / slack-textmeme / app.js View on Github external
'use strict'

var restify = require('restify')
var msRest = require('ms-rest')
var Connector = require('botconnector')
const Memes = require('./lib/memes')
const memes = new Memes()

// Initialize server
var server = restify.createServer()
server.use(restify.authorizationParser())
server.use(restify.bodyParser())

// Initialize credentials for connecting to Bot Connector Service
var appId = process.env.appId || 'textmeme'
var appSecret = process.env.appSecret || 'ec470402ed6d4f2c9e40e597bc4cff73'
var credentials = new msRest.BasicAuthenticationCredentials(appId, appSecret)

// Handle incoming message
server.post('/v1/messages', verifyBotFramework(credentials), (req, res) => {
  var msg = req.body
  console.log(req.body.text)
  const [name] = req.body.text.split(';')
  sendMessage(name)

  if (name === 'memes') {
github microsoft / botbuilder-js / samples / dialogs / prompts-ts / lib / app.js View on Github external
"use strict";
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
Object.defineProperty(exports, "__esModule", { value: true });
const botbuilder_1 = require("botbuilder");
const botbuilder_dialogs_1 = require("botbuilder-dialogs");
const restify = require("restify");
// Create server
let server = restify.createServer();
server.listen(process.env.port || process.env.PORT || 3978, function () {
    console.log(`${server.name} listening to ${server.url}`);
});
// Create adapter
const adapter = new botbuilder_1.BotFrameworkAdapter({
    appId: process.env.MICROSOFT_APP_ID,
    appPassword: process.env.MICROSOFT_APP_PASSWORD
});
// Add conversation state middleware
const conversationState = new botbuilder_1.ConversationState(new botbuilder_1.MemoryStorage());
adapter.use(conversationState);
// Listen for incoming requests 
server.post('/api/messages', (req, res) => {
    // Route received request to adapter for processing
    adapter.processActivity(req, res, (context) => __awaiter(this, void 0, void 0, function* () {
        if (context.activity.type === 'message') {
github microsoft / botbuilder-js / samples / hello-ts / lib / app.js View on Github external
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const botbuilder_1 = require("botbuilder");
const botbuilder_services_1 = require("botbuilder-services");
const restify = require("restify");
// Create server
let server = restify.createServer();
server.listen(process.env.port || process.env.PORT || 3978, function () {
    console.log(`${server.name} listening to ${server.url}`);
});
// Create adapter and listen to our servers '/api/messages' route.
const botFrameworkAdapter = new botbuilder_services_1.BotFrameworkAdapter({ appId: process.env.MICROSOFT_APP_ID, appPassword: process.env.MICROSOFT_APP_PASSWORD });
server.post('/api/messages', botFrameworkAdapter.listen());
// Initialize bot by passing it adapter
const bot = new botbuilder_1.Bot(botFrameworkAdapter);
// define the bot's onReceive message handler
bot.onReceive((context) => {
    context.reply(`Hello World`);
});
// END OF LINE
github SharePoint / sp-dev-fx-extensions / samples / react-msal-bot / bot / app.js View on Github external
/*-----------------------------------------------------------------------------
Name: react-msal-bot
Author: Franck Cornu (aequos) - Twitter @FranckCornu
Date: August 4th, 2018
Description: This sample shows how to handle Microsoft graph queries with an access token retrieved from a SharePoint site via the backchannel
-----------------------------------------------------------------------------*/
const restify = require('restify');
const builder = require('botbuilder');
const fetch = require('node-fetch');

// Setup Restify Server
const server = restify.createServer();
server.listen(process.env.port || process.env.PORT || 3978, function () {
   console.log('%s listening to %s', server.name, server.url); 
});
  
// Create chat connector for communicating with the Bot Framework Service
const connector = new builder.ChatConnector({
    appId: process.env.MicrosoftAppId,
    appPassword: process.env.MicrosoftAppPassword,
    stateEndpoint: process.env.BotStateEndpoint,
    openIdMetadata: process.env.BotOpenIdMetadata 
});

// Listen for messages from users 
server.post('/api/messages', connector.listen());

// Create an "in memory" bot storage. 
github OfficeDev / BotBuilder-MicrosoftTeams-node / samples / echo-bot-with-counter / src / app.ts View on Github external
// const STORAGE_CONFIGURATION_ID = '';
// // Default container name
// const DEFAULT_BOT_CONTAINER = '';
// // Get service configuration
// const blobStorageConfig = botConfig.findServiceByNameOrId(STORAGE_CONFIGURATION_ID);
// const blobStorage = new BlobStorage({
//     containerName: (blobStorageConfig.container || DEFAULT_BOT_CONTAINER),
//     storageAccountOrConnectionString: blobStorageConfig.connectionString,
// });
// conversationState = new ConversationState(blobStorage);

// Create the EchoBot.
const bot = new EchoBot(conversationState);

// Create HTTP server
const server = restify.createServer();
server.listen(process.env.port || process.env.PORT || 3978, () => {
    console.log(`\n${ server.name } listening to ${ server.url }`);
    console.log(`\nGet Bot Framework Emulator: https://aka.ms/botframework-emulator.`);
    console.log(`\nTo talk to your bot, open echobot-with-counter.bot file in the Emulator.`);
});

// Listen for incoming activities and route them to your bot for processing.
server.post('/api/messages', (req, res) => {
    adapter.processActivity(req, res, async (turnContext) => {
        // Call bot.onTurn() to handle all incoming messages.
        await bot.onTurn(turnContext);
    });
});