Installations
npm install restful-ng-mock
Developer Guide
Typescript
No
Module System
CommonJS
NPM Version
1.3.11
Score
74.2
Supply Chain
98.5
Quality
74.7
Maintenance
100
Vulnerability
100
License
Releases
Unable to fetch releases
Contributors
Unable to fetch Contributors
Languages
JavaScript (100%)
Developer
AmericanCouncils
Download Statistics
Total Downloads
1,080
Last Day
1
Last Week
2
Last Month
9
Last Year
93
GitHub Statistics
7 Stars
105 Commits
3 Forks
7 Watching
1 Branches
3 Contributors
Bundle Size
5.53 kB
Minified
2.03 kB
Minified + Gzipped
Package Meta Information
Latest Version
0.3.0
Package Id
restful-ng-mock@0.3.0
Size
14.22 kB
NPM Version
1.3.11
Total Downloads
Cumulative downloads
Total Downloads
1,080
Last day
0%
1
Compared to previous day
Last week
-33.3%
2
Compared to previous week
Last month
80%
9
Compared to previous month
Last year
-26.2%
93
Compared to previous year
Daily Downloads
Weekly Downloads
Monthly Downloads
Yearly Downloads
restful-ng-mock
When you're writing an Angular app for those APIs, you will often want to create a client-side mock that simulates the server. This is typically done with $httpBackend
, but manually adding all your web methods with that module's low-level interface can be tedious and error-prone. restful-ng-mock
is a frontend to $httpBackend
that handles a lot of the most common stuff for you, such as converting responses to JSON and providing sensible default implementations of the standard CRUD methods.
Installation
After you've downloaded the restful-ng-mock component with bower, add the
usual lines in app.js (to restfulNgMock
) and index.html (to
components/restful-ng-mock/build/restful-ng-mock.js
).
Basic mocks
Create a mock object for each major resource on your server under a given
URL prefix. For example, suppose you have some URLs available under /items
:
1angular.module('myApp').factory('mockItems', [ 2'basicMock', // This service is from restful-ng-mock 3function(basicMock) { 4 var items = { 5 1: { id: 1, name: 'Foo'}, 6 2: { id: 2, name: 'Bar'} 7 }; 8 var itemsMock = basicMock('/items'); 9 10 // This handles requests to '/items' 11 itemsMock.route('GET', '', function() { 12 return items; 13 }); 14 15 // A question mark allows an arbitrary argument 16 // So, this handles requests to '/items/<n>' for any single value <n> 17 itemsMock.route('GET', '/?', function(request) { 18 var id = request.pathArgs[0]; 19 // Null and undefined values will automatically be transformed to 404 responses 20 return items[id]; 21 }); 22 23 // This handles POST requests to '/items/<n>/form_voltron' 24 itemsMock.route('POST', '/?/form_voltron', function(request) { 25 // request.url is a purl url object, see https://github.com/allmarkedup/purl 26 // Here we require that the URL was like /items/123/form_voltron?password=abc123 27 if (request.url.param('password') == 'abc123') { 28 // If the request had a JSON body, then it is automatically parsed and 29 // made available in request.body 30 if (request.body.pilot) { 31 return { result: "I'll form the head!", pilot: request.body.pilot }; 32 } else { 33 return { result: "I guess John will form the head.", pilot: "John" }; 34 } 35 } else { 36 // Return HttpError for non-200 responses 37 return new this.HttpError(400, "You're not a member of the Voltron team!"); 38 } 39 }); 40}]);
Post-processing
The route
method returns an object that you can use to further customize the mock's behavior. Use the addPostProc
method to add a function which accepts the data returned by the route implementation and can return a modified version of that data:
1var route = itemsMock.route('GET', '', function() { 2 return items; 3}); 4route.addPostProc(data, function(data, request) { 5 data.reverse(); 6 return data; 7}
This is convenient when you are doing the same or similar transformations in many different places in your mock.
Resource mocks
Often, a server may be implementing a database-like service with the usual CRUD actions. There is a convenience service resourceMock
that makes this easier:
1angular.module('myApp').factory('mockPeople', [ 2'resourceMock', // This service is from restful-ng-mock 3function(resourceMock) { 4 var people = { 5 1: { id: 1, name: 'Alice'}, 6 2: { id: 2, name: 'Bob'} 7 }; 8 var peopleMock = resourceMock('/people', people); 9}]);
This automatically provides all the usual CRUD methods:
- Get a list of people at
GET /people
. Indexes are returned as arrays rather than objects, even though the internal data store is an object. - Create new people with
POST /people
. They are automatically assigned a new random numeric id. - Retrieve an individual person with id 2 at
GET /people/2
. - Update them with a new object at
PUT /people/2
. - Delete them with
DELETE /people/2
.
You can override the default implementations of these by setting new methods (respectively, indexAction
, createAction
, showAction
, updateAction
, and deleteAction
) on the mock object. The default method is available to these through the parent
object:
1// Let's anonymize the first person returned by every index request 2peopleMock.indexAction = function(request) { 3 var people = this.parent.indexAction.call(this, request); 4 if (people.length > 0) { 5 people[0].name = "John Doe"; 6 } 7 return people; 8}
The resource mock also supports all the same methods as basicMock
, which is convenient for adding RPC-ish stuff and other not-strictly-RESTful methods:
1peopleMock.route('POST', '/?/jump', function(request) { 2 return { result: "I jumped! Now what?" }; 3});
The automatic routes themselves are available as attributes under the names indexRoute
, showRoute
, etc., which means you can apply post processors. There are some convenience
methods on resourceMock for common post-processing situations:
addIndexFilter(fieldName[, filterFunc])
: Allows you to specify a GET argument to filter results by a particular field value. You can optionally specify a filter function, which is given the GET argument value and a data object, and should return true if the object matches the filter specified by the value.addIndexArrayFilter(fieldName[, sep[, filterFunc]])
: A filter that checks against a list of acceptable values. The default separator is a comma.addIndexPagination([skipName, limitName])
: Specify GET arguments used to retrieve a subset of the results. TheskipName
argument slices off results from the beginning of the array, and thelimitName
argument sets a maximum number of results to return; if you don't specify these, they are simply "skip" and "limit" by default.addLabeller(singleLabel, pluralLabel)
: Puts the data returned under a key in a containing object. ThepluralLabel
is used for index results, and thesingleLabel
is used for the results from all other actions. Note that this must be applied after the other index-related filters above.addSingletonPostProcs(func)
: Apply the same post processing function to the show, update, create, and destroy actions.
Options
There are various options you can enable on both types of mock. These can be set with an additional argument to the constructor, or by calling the setOptions
method:
1var oneMock = basicMock('/foo', { debug: true }); 2var twoMock = resourceMock('/bar', stuff); 3twoMock.setOptions({ httpResponseInfoLabel: 'response' });
These options are available for both basicMock
and resourceMock
:
debug
: If set totrue
, then all HTTP responses will be logged with console.log. Alternately, you can provide a function here, and it will be called with the request object, the response info object, and the response data.httpResponseInfoLabel
: If set to a string, then HTTP response info will be embedded in all JSON responses under this key. The response info object includes the HTTP code and a status message.
No vulnerabilities found.
Reason
no binaries found in the repo
Reason
0 existing vulnerabilities detected
Reason
Found 3/26 approved changesets -- score normalized to 1
Reason
0 commit(s) and 0 issue activity found in the last 90 days -- score normalized to 0
Reason
no effort to earn an OpenSSF best practices badge detected
Reason
security policy file not detected
Details
- Warn: no security policy file detected
- Warn: no security file to analyze
- Warn: no security file to analyze
- Warn: no security file to analyze
Reason
project is not fuzzed
Details
- Warn: no fuzzer integrations found
Reason
license file not detected
Details
- Warn: project does not have a license file
Reason
branch protection not enabled on development/release branches
Details
- Warn: branch protection not enabled for branch 'master'
Reason
SAST tool is not run on all commits -- score normalized to 0
Details
- Warn: 0 commits out of 7 are checked with a SAST tool
Score
2.7
/10
Last Scanned on 2025-01-27
The Open Source Security Foundation is a cross-industry collaboration to improve the security of open source software (OSS). The Scorecard provides security health metrics for open source projects.
Learn More