Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
Browse files

Client stuff stable

  • Loading branch information...
commit 77351c7e179d30f47fe63ae3498dc43576b5c43b 1 parent fe540b3
@dncrews dncrews authored
View
11 Makefile
@@ -0,0 +1,11 @@
+
+build: components index.js
+ @component build --dev
+
+components: component.json
+ @component install --dev
+
+clean:
+ rm -fr build components template.js
+
+.PHONY: clean
View
5 app.js
@@ -7,10 +7,11 @@ var app = express();
app.use(express.bodyParser());
app.use(express.static(__dirname + '/assets'));
+app.use(express.static(__dirname + '/build'));
-app.get('/sample', function(req, res, next) {
+app.get('/sample/:type', function(req, res, next) {
console.log(req.headers);
- res.send('I DID IT I\'M SO AWESOME');
+ res.send('I DID IT I\'M SO AWESOME! (' + req.params.type + ')');
});
app.listen(process.env.PORT || 5000, function() {
View
20 assets/index.html
@@ -4,18 +4,22 @@
<link rel="stylesheet" href="vendor/bootstrap-3.0.0/css/bootstrap-theme.min.css">
</head>
<body>
- <div class="container" data-ng-controller="SuperagentController">
- <span data-ng-superagent='{
- "x-request-id" : "654654654",
- "locale" : "es",
- "fsSessionId" : "987456321"
- }'></span>
- <button class="btn btn-success" data-ng-click="doIt()">Click ME</button>
+ <div class="container" data-ng-controller="ngSuperagentController" data-superagent-init>
+ <button class="btn btn-success" data-ng-click="fireWithoutInit()">Go ngManual</button>
+ <button class="btn btn-success" data-ng-click="fireWithInit()">Go ngDirective</button>
<h1 data-ng-bind="text"></h1>
</div>
+ <div class="container" data-ng-controller="fsSuperagentController">
+ <button class="btn btn-success" data-ng-click="fireWithFS()">Go FS</button>
+ </div>
+
+ <script src="vendor/angular-1.0.8.min.js"></script>
+ <script src="build.js"></script>
+ <script src="js/my_app.js"></script>
+ <!--
<script src="vendor/superagent.js"></script>
<script src="vendor/superagent-defaults.js"></script>
- <script src="vendor/angular-1.0.8.min.js"></script>
<script src="js/app.js"></script>
+ -->
</body>
</html>
View
71 assets/js/my_app.js
@@ -0,0 +1,71 @@
+
+console.error('here', window.angular);
+(function(ng, fsSuperagent) {
+ "use strict";
+
+ var module = ng.module('ngSuperagent', []);
+
+ fsSuperagent.angular(module);
+
+ module.controller('fsSuperagentController', [
+ "$scope",
+
+ function($scope) {
+ $scope.fireWithFS = function() {
+ var FS = {
+ superagent : fsSuperagent.obj()
+ };
+ FS.superagent
+ .get('/sample/fs')
+ .end(function(err, response) {
+ if (err) return console.error('err', err);
+ alert(response.text);
+ });
+ };
+ }
+ ]);
+
+ module.controller('ngSuperagentController', [
+ "$scope",
+ "$superagent",
+ "myService",
+
+ function($scope, $superagent, service) {
+ $scope.text = 'ready';
+ $scope.fireWithInit = function() {
+ service.makeCall(function(response) {
+ $scope.text = response.text;
+ });
+ };
+ $scope.fireWithoutInit = function() {
+ $superagent
+ .get('/sample/setScope')
+ .$setScope($scope)
+ .end(function(err, response) {
+ if (err) return console.error('err', err);
+ $scope.text = response.text;
+ });
+ };
+ }
+ ]);
+
+ module.factory('myService', [
+ '$superagent',
+
+ function($superagent) {
+ function makeCall(next) {
+ $superagent
+ .get('/sample/directive')
+ .end(function(err, response) {
+ if (err) return console.error('err', err);
+ next(response);
+ });
+ }
+ return {
+ makeCall : makeCall
+ };
+ }
+ ]);
+
+
+})(window.angular, window.fsSuperagent);
View
4 bin/tests
@@ -0,0 +1,4 @@
+#/usr/bin/env bash
+
+# NODE_ENV=test `pwd`/node_modules/.bin/mocha --require blanket --reporter json-cov test/server/
+NODE_ENV=test `pwd`/node_modules/.bin/mocha --reporter spec test/server/
View
23 component.json
@@ -0,0 +1,23 @@
+{
+ "name": "fs-superagent",
+ "repo": "fs-webdev/fs-superagent",
+ "description": "FamilySearch Superagent",
+ "version": "0.0.1",
+ "keywords": [],
+ "dependencies": {
+ "visionmedia/debug": "*",
+ "component/url": "*",
+ "CamShaft/superagent-defaults": "*"
+ },
+ "development": {},
+ "license": "MIT",
+ "main": "lib/client/index.js",
+ "scripts": [
+ "lib/client/helpers/readCookies.js",
+ "lib/client/helpers/readHeaders.js",
+ "lib/fs-superagent.js",
+ "lib/client/ng-fs-superagent.js",
+ "lib/client/obj-fs-superagent.js",
+ "lib/client/index.js"
+ ]
+}
View
5 index.js
@@ -0,0 +1,5 @@
+if ('undefined' === typeof window) {
+ module.exports = require('./lib/fs-superagent');
+} else {
+ module.exports = require('./lib/client');
+}
View
19 lib/client/helpers/readCookies.js
@@ -0,0 +1,19 @@
+/*global console:false,module:false,require:false,document:false,window:false,XMLHttpRequest:false */
+'use strict';
+
+var cookies;
+
+module.exports = function readCookies() {
+ if (cookies) return cookies;
+ var c, C, i;
+
+ c = document.cookie.split('; ');
+ cookies = {};
+
+ for(i=c.length-1; i>=0; i--){
+ C = c[i].split('=');
+ cookies[C[0]] = C[1];
+ }
+
+ return cookies;
+};
View
18 lib/client/helpers/readHeaders.js
@@ -0,0 +1,18 @@
+// I'm not sure this does what I wanted it to do.
+// These things are handled elsewhere (HAProxy, accept-language, etc)
+
+
+/*global console:false,module:false,require:false,document:false,window:false,XMLHttpRequest:false */
+'use strict';
+
+var headers;
+
+module.exports = function readHeaders() {
+ if (headers) return headers;
+ var req;
+ req = new XMLHttpRequest();
+ req.open('GET', document.location, false);
+ req.send(null);
+ headers = req.getAllResponseHeaders().toLowerCase();
+ return headers;
+};
View
7 lib/client/index.js
@@ -0,0 +1,7 @@
+/*global console:false,module:false,require:false,document:false,window:false,XMLHttpRequest:false */
+'use strict';
+
+module.exports = {
+ 'angular' : require('./ng-fs-superagent'),
+ 'obj' : require('./obj-fs-superagent')
+};
View
54 lib/client/ng-fs-superagent.js
@@ -0,0 +1,54 @@
+/*global console:false,module:false,require:false,document:false,window:false,XMLHttpRequest:false */
+'use strict';
+
+var fsSuperagent = require('../fs-superagent')
+ , readCookies = require('./helpers/readCookies');
+ // , readHeaders = require('./helpers/readHeaders');
+
+module.exports = function(app) {
+
+ /**
+ * Optional $superagent init directive
+ */
+ app.directive('superagentInit', [
+ '$superagent',
+
+ function($superagent) {
+ return {
+ restrict: 'EA',
+ link: function(scope) {
+ $superagent.on('request', function(request) {
+ request.handleEnd(function(cb, params) {
+ scope.$apply(function() {
+ cb.apply(null, params);
+ });
+ });
+ });
+ }
+ };
+ }
+ ]);
+
+ /**
+ * $superagent "Service"
+ */
+ app.factory('$superagent', [
+
+ function() {
+ return fsSuperagent({
+ // headers: readHeaders(),
+ cookies: readCookies()
+ })
+ .on('request', function(request) {
+ request.$setScope = function(scope) {
+ request.handleEnd(function(cb, params) {
+ scope.$apply(function() {
+ cb.apply(null, params);
+ });
+ });
+ return request;
+ };
+ });
+ }
+ ]);
+};
View
13 lib/client/obj-fs-superagent.js
@@ -0,0 +1,13 @@
+/*global console:false,module:false,require:false,document:false,window:false,XMLHttpRequest:false */
+'use strict';
+
+var fsSuperagent = require('../fs-superagent')
+ , readCookies = require('./helpers/readCookies');
+ // , readHeaders = require('./helpers/readHeaders');
+
+module.exports = function() {
+ return fsSuperagent({
+ // headers: readHeaders(),
+ cookies: readCookies()
+ });
+};
View
137 lib/fs-superagent.js
@@ -0,0 +1,137 @@
+/**
+ * Create a superagent context from the supplied cookies and headers
+ * Applies some defaults like:
+ *
+ * - response time metrics (Future)
+ * - send the x-request-id header
+ * - send the authorization if the user is logged in
+ *
+ * Also provides some additional opt-ins:
+ * - Setting locale
+ * - Setting sessionId to query
+ * - Error handling (Future)
+ * - Timeout handling (Future)
+ *
+ * Example
+ *
+ * app.get('/', function(req, res) {
+ * req.superagent
+ * .get('http://example.com')
+ * .end(function(err, res) {
+ * // The request has the default headers applied
+ * // do app work here
+ * })
+ * });
+ */
+
+/*global Buffer:false,clearInterval:false,clearTimeout:false,console:false,exports:false,global:false,module:false,process:false,querystring:false,require:false,setInterval:false,setTimeout:false,__filename:false,__dirname:false */
+'use strict';
+
+var superagent = require('superagent-defaults')
+ , debug = require('debug')('fsSuperagent')
+ , url = require('url');
+
+module.exports = fsSuperagent;
+
+function fsSuperagent(config) {
+ var context = superagent()
+ , cookies = config.cookies || {}
+ , headers = config.headers || {};
+ return context.on('request', function(request) {
+ var reqId = headers['x-request-id']
+ , sessId = cookies.fssessionid
+ , info = url.parse(request.url)
+ , addToLogs = {}
+ , endHandler;
+
+ // TODO: Add metric logging (START)
+
+ request.set('accept', 'application/json');
+
+ // Do we want a default timeout on the client?
+ request.timeout(20000);
+
+ if (reqId) request.set('x-request-id', reqId);
+ if (sessId) request.set('authorization', 'Bearer ' + sessId);
+
+ request.setLocale = function(locale) {
+ locale = (locale || headers['accept-language'] || 'en').substr(0,2);
+ request.query({ 'locale' : locale });
+ return request;
+ };
+
+ request.setSessionId = function(sessionName) {
+ request.query(sessionName, sessId);
+ return request;
+ };
+
+ request.handleErrors = function() {
+ request.on('error', function errorHandler(err) {
+ // TODO: Add Metric logging (FAILURE)
+ if (err.timeout) {
+ // TODO: Do something to register a timeout to the server
+ }
+ // TODO: Do something to register an error with the server
+ });
+ return request;
+ };
+
+ request.addLog = function(name, value) {
+ if (typeof name === 'string' && typeof value === 'string') {
+ addToLogs[name] = value;
+ }
+ if (typeof name === 'object') {
+ for (var key in name) {
+ if (name.hasOwnProperty(key)) {
+ addToLogs[key] = name[key];
+ }
+ }
+ }
+ return request;
+ };
+
+ request.handleEnd = function(handler) {
+ if (typeof handler === 'function') {
+ endHandler = handler;
+ }
+ };
+
+
+ // We have to overwrite the request.end to fix the error handling problems
+ request._end = request.end;
+ request.end = function(cb) {
+
+ function doCb() {
+ if(typeof endHandler === 'function') {
+ return endHandler(cb, arguments);
+ }
+ cb.apply(null, arguments);
+ }
+
+ // Default to no error callback
+ var okCB = function(response) {
+ doCb(response);
+ };
+ if (cb.length === 2) {
+ // 200 callback requires empty first param
+ okCB = function(response) {
+ doCb(null, response);
+ };
+ // Bind the error callback for errors
+ request
+ .on('error', function(err) {
+ // handle errors too?
+ doCb(err);
+ });
+ }
+
+ request._end(function(response) {
+ // TODO: Add metric logging (FINISHED)
+ console.log('addToLogs', addToLogs);
+ console.log('contentLength', response.headers['content-length']);
+ console.log('status' , response.status);
+ okCB(response);
+ });
+ };
+ });
+}
View
69 lib/node/index.js
@@ -0,0 +1,69 @@
+/**
+ * Description:
+ * Creates req.superagent from fs-superagent.
+ * Adds some additional defaults:
+ *
+ * - Metric logging
+ * - Request closing on client close
+ * Creates a req.superagent() function which add some nice defaults and log metrics to a superagent call.
+ *
+ * Example
+ *
+ * app.get('/', function(req, res) {
+ * req.superagent
+ * .get('http://example.com')
+ * .end(function(err, res) {
+ * // The request has the default headers applied
+ * // do app work here
+ * })
+ * });
+ */
+
+/*global Buffer:false,clearInterval:false,clearTimeout:false,console:false,exports:false,global:false,module:false,process:false,querystring:false,require:false,setInterval:false,setTimeout:false,__filename:false,__dirname:false */
+'use strict';
+
+/**
+ * Module deps
+ */
+var url = require('url')
+ , fsSuperagent = require('../fs-superagent');
+
+module.exports = function() {
+ return function superagent(req, res, next) {
+ var context = fsSuperagent({
+ 'cookies' : req.cookies,
+ 'headers' : req.headers
+ });
+ context.on('request', function(request) {
+ var info = url.parse(request.url)
+ , addToLogs
+ , done = req.metric.profile('response_time', {
+ lib: 'fs-superagent',
+ protocol: (info.protocol || '').replace(':', ''),
+ hostname: info.hostname,
+ port: info.port,
+ path: info.path
+ });
+
+ function closeRequest() {
+ request.abort();
+ }
+
+ req.on('close', closeRequest);
+
+ request.on('response', function(response) {
+ var metricData = {
+ code: response.status,
+ bytes: response.headers['content-length']
+ };
+ for (var key in addToLogs) {
+ if (addToLogs.hasOwnProperty(key)) {
+ metricData[key] = addToLogs[key];
+ }
+ }
+ req.removeListener('close', closeRequest);
+ done(metricData);
+ });
+ });
+ };
+};
View
5 package.json
@@ -4,7 +4,7 @@
"description": "Anguar $superagent",
"main": "app.js",
"scripts": {
- "test": "echo \"Error: no test specified\" && exit 1"
+ "test": "foreman run sh ./bin/tests",
},
"repository": {
"type": "git",
@@ -16,7 +16,8 @@
"url": "https://github.com/dncrews/ng-superagent/issues"
},
"dependencies": {
- "express": "~3.4.1"
+ "express": "~3.4.1",
+ "debug": "~0.7.2"
},
"devDependencies": {
"karma-script-launcher": "~0.1.0",
View
21 test/client/karma.conf.js
@@ -6,24 +6,29 @@ module.exports = function(config) {
// base path, that will be used to resolve files and exclude
basePath: '../..',
- frameworks: ['mocha', 'commonjs'],
+ frameworks: [ 'ng-scenario' ],
+
+ // frameworks: ['mocha', 'commonjs'],
// list of files / patterns to load in the browser
files: [
- 'assets/js/*.js',
- 'client/*.js',
- 'test/client/*.js'
+ 'assets/vendor/superagent.js',
+ 'assets/vendor/superagent-defaults.js',
+ 'assets/vendor/angular-1.0.8.min.js',
+ 'assets/js/app.js',
+ 'test/client/superagent.js'
],
// list of files to exclude
exclude: [
- 'client/main.js'
+ // 'client/main.js'
],
preprocessors: {
- 'assets/js/*.js' : 'coverage',
- 'client/*.js': ['commonjs'],
- 'test/client/*.js': ['commonjs']
+ 'assets/js/*.js' : 'coverage'
+ // 'assets/js/*.js' : 'coverage',
+ // 'client/*.js': ['commonjs'],
+ // 'test/client/superagent.js': ['commonjs']
},
// use dots reporter, as travis terminal does not support escaping sequences
View
8 test/client/superagent.js
@@ -0,0 +1,8 @@
+/*global describe:false,it:false,console:false */
+'use strict';
+
+describe('$superagent', function() {
+ it('what', function() {
+ console.log('here');
+ });
+});
Please sign in to comment.
Something went wrong with that request. Please try again.