Installations
npm install @tg-resources/superagent
Releases
Developer
Developer Guide
Module System
CommonJS
Min. Node Version
Typescript Support
Yes
Node Version
18.19.1
NPM Version
lerna/8.1.9/node@v18.19.1+x64 (linux)
Statistics
5 Stars
342 Commits
5 Forks
18 Watching
10 Branches
8 Contributors
Updated on 20 Nov 2024
Languages
TypeScript (96.9%)
JavaScript (2.78%)
Shell (0.32%)
Total Downloads
Cumulative downloads
Total Downloads
31,501
Last day
100%
6
Compared to previous day
Last week
291.2%
133
Compared to previous week
Last month
18.8%
240
Compared to previous month
Last year
-58.2%
4,428
Compared to previous year
Daily Downloads
Weekly Downloads
Monthly Downloads
Yearly Downloads
tg-resources
Abstractions on-top of
superagent
andfetch
(or other Ajax libraries) for communication with REST. Targeted mostly againstDjango Rest Framework (DRF)
running onDjango
so some logic might not be applicable for other frameworks.
Installing
Using NPM
1npm i tg-resources 2 3# And add fetch backend 4npm i @tg-resources/fetch 5 6# Or use superagent backend 7npm i @tg-resources/superagent
Or using Yarn
1yarn add tg-resources 2 3# And fetch backend 4yarn add @tg-resources/fetch 5 6# Or use superagent backend 7yarn add @tg-resources/superagent
Polyfills for fetch
When you are targeting browsers without native support for fetch or running this on node versions before 17 then you need to provide polyfills for the fetch globals. The easiest way to do it is to add @tg-resources/fetch-runtime.
Alternatively you can also just use your own polyfill if you want to. In that case the methods should be available in the root scope (e.g. window/self for browsers or global for node).
Does it work on react native?
YES
Using with hermes engine
With the version 4.0.0 hermes is fully supported as we have replaced lodash.template
with our own url token replacement helper. :tada:
Using signal
with react-native
Use abortcontroller-polyfill until https://github.com/facebook/react-native/issues/18115 is resolved in react-native core. The polyfill does not actually close the connection, but instead ensures the fetch rejects the promise with AbortError
. To use the polyfill add the following to the top of your app entrypoint:
import 'abortcontroller-polyfill/dist/polyfill-patch-fetch'
Basic Usage
1import { Router } from "tg-resources" 2import { FetchResource: Resource } from "@tg-resources/fetch" 3 4const onLoad = result => console.log(result); 5const onError = result => console.error(result); 6 7 8const api = new Router({ 9 cats: new Resource('/cats'), 10 cat: new Resource('/cats/${pk}') 11}, { 12 apiRoot: '/api/v1' // Set api root 13}); 14 15const apiRouter = createRouter({ 16 cats: '/cats', 17 cat: '/cats/${pk}', 18}, { 19 apiRoot: '/api/v1', // Set api root 20}, Resource); 21 22// Do a get request to /api/v1/cats?gender=M 23api.cats.fetch(null, {gender: 'M'}).then(onLoad, onError); 24apiRouter.cats.fetch(null, {gender: 'M'}).then(onLoad, onError); 25 26// Do a head request to /api/v1/cats?gender=M 27api.cats.head(null, {gender: 'M'}).then(onLoad, onError); 28apiRouter.cats.head(null, {gender: 'M'}).then(onLoad, onError); 29 30// Do a post request to /api/v1/cats with data: {name: 'Twinky', gender: 'M'} 31api.cats.post(null, {name: 'Twinky', gender: 'M'}).then(onLoad, onError); 32apiRouter.cats.post(null, {name: 'Twinky', gender: 'M'}).then(onLoad, onError); 33 34// Do a patch request to /api/v1/cats/1 with data: {name: 'Tinkelberg'} 35api.cat.patch({pk: 1}, {name: 'Tinkelberg'}).then(onLoad, onError); 36apiRouter.cat.patch({pk: 1}, {name: 'Tinkelberg'}).then(onLoad, onError); 37 38// Do a put request to /api/v1/cats with data: {pk: 1, name: 'Twinky'} 39api.cats.put(null, {pk: 1, name: 'Twinky', gender: 'M'}).then(onLoad, onError); 40apiRouter.cats.put(null, {pk: 1, name: 'Twinky', gender: 'M'}).then(onLoad, onError); 41 42// Do a delete request to /api/v1/cats/1 with data: {'free':'yes'} 43api.cat.del({pk: 1}, {free: 'yes'}).then(onLoad, onError); 44apiRouter.cat.del({pk: 1}, {free: 'yes'}).then(onLoad, onError);
Please note that the router is useful for providing default configuration and grouping endpoints. It's still possible to use Resources without a router(see Resource api)
Configuration
apiRoot
(String): Base for all resource pathsheaders
(Object|Function: Object): Optional Function or Object which can be used to add any additional headers to requests.cookies
(Object|Function): Optional Function or Object which can be used to add any additional cookies to requests. Please note that in modern browsers this is disabled due to security concerns.mutateResponse
(Function): Optional function with signature(responseData, rawResponse: ResponseWrapper, resource: Resource, requestConfig: Object) => responseData
which can be used to mutate response data before resolving it. E.g. This can be used to provide access to raw response codes and headers to your success handler.mutateError
(Function): Optional function with signature(error: ResourceErrorInterface, rawResponse: ResponseWrapper, resource: Resource, requestConfig: Object) => error
which can be used to mutate errors before rejecting them. E.g. This can be used to provide access to raw response codes and headers to your error handler.statusSuccess
(Array[int]|number): Array (or a single value) of status codes to treat as a success. Default: [200, 201, 204]statusValidationError
(Array[int]|number): Array (or a single value) of status codes to treat as ValidationError. Default: [400]defaultAcceptHeader
(String): Default accept header that is automatically added to requests (only ifheaders.Accept=undefined
). Default:'application/json'
parseErrors
(Function): Function with signature(errorText, parentConfig) => [nonFieldErrors, errors]
which is used to parse response errors into a ValidationError object. The default handler is built for Django/DRF errors.prepareError
(Function): Function with signature(err, parentConfig) => mixed
which is used to normalize a single error. The default handler is built for Django/DRF errors.mutateRawResponse
(Function): Advanced usage: Optional function with signature(rawResponse: ResponseWrapper, requestConfig: Object) => rawResponse
which can be used to mutate the response before it is resolved toresponseData
or aResourceErrorInterface
subclass. Use the source ofResponseWrapper
,SuperagentResponse
andResource::ensureStatusAndJson
for guidance.withCredentials
(bool): Allow request backend to send cookies/authentication headers, useful when using same API for server-side rendering.allowAttachments
(bool): Allow POST like methods to send attachments.signal
: (AbortSignal): Pass in an AbortSignal object to abort the request when desired. Only supported via request config. Default: [null]. For react-native a polyfill is needed.
Error handling
With tg-resources, all errors are Rejected. The logic is best described with an example:
1const resource = new Resource('user/login'); 2 3const errorHandler = (error) => { 4 // Network error occurred 5 if (error.isNetworkError) { 6 console.error({ 7 type: 'NETWORK_FAILED', 8 error, 9 }); 10 } else if (error.isAbortError) { 11 // Request was aborted 12 console.error({ 13 type: 'ABORTED', 14 error, 15 }); 16 } else if (error.isValidationError) { 17 // Validation error occurred (e.g.: wrong credentials) 18 console.error({ 19 type: 'VALIDATION_ERROR', 20 error, 21 }); 22 } else { 23 // As a last resort, also handle invalid response codes 24 console.error({ 25 type: 'SERVER_ERROR', 26 error, 27 }); 28 } 29}; 30 31const payload = { 32 user: 'foo', 33 passwrod: 'bar', 34}; 35 36resource.post(null, payload).then( 37 (user) => 38 console.log({ 39 type: 'LOGGED_IN', 40 data: { 41 user, 42 }, 43 }), 44 errorHandler 45);
API
createRouter
Creates type-safe Router
instance.
Arguments
routes
(Object): Object matching pattern{ [key]: string | { [key]: string } }
. String values are used as endpoints to create resource. For more info see Resource API This can be nested, meaning new router is created for object types found.config
(Object): Object containing config for top level router. See ConfigurationresourceKlass
Resource: Resource class that implements backend. This allows any of the backends to be used when creatingRouter
.
Resource
Construct a new resource for loading data from a single (or dynamic) endpoint
Arguments
apiEndpoint
(string): Endpoint used for this resource. Supports ES6 token syntax, e.g: "/foo/bar/${pk}"config
(Object): Object containing config for this resource. See Configuration
Tokenized endpoints
The Resource module also supports dynamic urls by supporting ES6 token syntax. Request methods
can then provide values as an object using the first argument kwargs
.
So for example:
1new Resource('/foo/bar/${pk}').get({ pk: 1 }).then((x) => x);
Would result in a GET request to /foo/bar/1
Returns
(Resource): Returns instance of Resource
.
Resource.fetch
Do a get request to the resource endpoint with optional kwargs and query parameters.
Arguments
kwargs=null
(Object): Object containing the replacement values if the resource uses tokenized urlsquery=null
(Object|string): Query parameters to use when doing the request.requestConfig=null
(Object): Configuration overrides, useful when using same API for server-side rendering.
Resource.options
Alias for Resource.fetch(kwargs, query, requestConfig)
with options
method.
Resource.head
Alias for Resource.fetch(kwargs, query, requestConfig)
with head
method.
Returns
(Promise): Returns a Promise
that resolves to the remote result or throws if errors occur.
Resource.post
Do a method
request to the resource endpoint with optional kwargs and query parameters.
Arguments
kwargs=null
(Object): Object containing the replacement values if the resource uses tokenized urlsdata=null
(Object|string): Query parameters to use when doing the request.query=null
(Object|string): Query parameters to use when doing the request.attachments=null
(Array): Attachments, creates multipart requestrequestConfig=null
(Object): Configuration overrides, useful when using same API for server-side rendering.
Returns
(Promise): Returns a Promise
that resolves to the remote result or throws if errors occur.
Resource.patch
Alias for Resource.post(kwargs, data, query, attachments, requestConfig)
with patch
method.
Resource.put
Alias for Resource.post(kwargs, data, query, attachments, requestConfig)
with put
method.
Resource.del
Alias for Resource.post(kwargs, data, query, attachments, requestConfig)
with del
method.
ResourceErrorInterface
Generic base class for all errors that can happen during requests
Attributes
isNetworkError
(bool): Alwaysfalse
isInvalidResponseCode
(bool): Alwaysfalse
isValidationError
(bool): Alwaysfalse
NetworkError
Error class used for all network related errors
Extends ResourceErrorInterface
and overwrites:
isNetworkError
(bool): Alwaystrue
Attributes
error
(Error): Original Error object that occured during network transport
AbortError
Error class used when a request is aborted
Extends ResourceErrorInterface
and overwrites:
isAbortError
(bool): Alwaystrue
Attributes
error
(Error): Original Error object that was raised by the request engine
InvalidResponseCode
Error class used when unexpected response code occurs
Extends ResourceErrorInterface
and overwrites:
isInvalidResponseCode
(bool): Alwaystrue
Attributes
statusCode
(string): Response status coderesponseText
(int): Response body text
RequestValidationError
Error class used when backend response code is in config.statusValidationError
.
Extends InvalidResponseCode
and overwrites:
isInvalidResponseCode
(bool): Alwaysfalse
isValidationError
(bool): Alwaystrue
Attributes
errors
: (ValidationErrorInterface|any): The result fromrequestConfig.parseError
ValidationErrorInterface
Error types returned by the default error parser.
Supports iteration (map/forEach/for .. of/etc)
Attributes
errors
: (any): Errors and error messages.
Types
Since DRF errors can be arbitrarily nested and one field can have multiple errors, some specific types of interest:
SingleValidationError
: Errors for a single field the.errors
attribute is a list of strings.ValidationError
: Errors for an object,.errors
is an object with field names as keys.ListValidationError
: Errors related to list of objects..errors
is a list ofValidationErrorInterface
.
Methods
(*) Not applicable to SingleValidationError
hasError
Returns
(bool): True if there are any errors.
getError
*
Get field specific error
Arguments
fieldName
(Array|string) : Field name or path to child error, e.g['parent', 'child']
or array indexes forListValidationError
[allowNonField=false]
(bool): If true, also check for nonFieldErrors if the specified field does not have an error
Returns
(any): Returns a normalized error for fieldName
or null
firstError
*
Get first error normalized to a string for this ValidationError
Arguments
[allowNonField=false]
(bool): If true, also check for nonFieldErrors
Returns
(any): First error as a string
or null
License
MIT © Thorgate
No vulnerabilities found.
Reason
22 commit(s) and 0 issue activity found in the last 90 days -- score normalized to 10
Reason
no dangerous workflow patterns detected
Reason
no binaries found in the repo
Reason
license file detected
Details
- Info: project has a license file: LICENSE:0
- Warn: project license file does not contain an FSF or OSI license.
Reason
Found 2/18 approved changesets -- score normalized to 1
Reason
detected GitHub workflow tokens with excessive permissions
Details
- Warn: no topLevel permission defined: .github/workflows/release-drafter.yml:1
- Warn: no topLevel permission defined: .github/workflows/run-tests.yml:1
- Info: no jobLevel write permissions found
Reason
dependency not pinned by hash detected -- score normalized to 0
Details
- Warn: third-party GitHubAction not pinned by hash: .github/workflows/release-drafter.yml:12: update your workflow using https://app.stepsecurity.io/secureworkflow/thorgate/tg-resources/release-drafter.yml/master?enable=pin
- Warn: GitHub-owned GitHubAction not pinned by hash: .github/workflows/run-tests.yml:16: update your workflow using https://app.stepsecurity.io/secureworkflow/thorgate/tg-resources/run-tests.yml/master?enable=pin
- Warn: GitHub-owned GitHubAction not pinned by hash: .github/workflows/run-tests.yml:17: update your workflow using https://app.stepsecurity.io/secureworkflow/thorgate/tg-resources/run-tests.yml/master?enable=pin
- Warn: GitHub-owned GitHubAction not pinned by hash: .github/workflows/run-tests.yml:20: update your workflow using https://app.stepsecurity.io/secureworkflow/thorgate/tg-resources/run-tests.yml/master?enable=pin
- Warn: third-party GitHubAction not pinned by hash: .github/workflows/run-tests.yml:36: update your workflow using https://app.stepsecurity.io/secureworkflow/thorgate/tg-resources/run-tests.yml/master?enable=pin
- Info: 0 out of 3 GitHub-owned GitHubAction dependencies pinned
- Info: 0 out of 2 third-party GitHubAction dependencies pinned
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
SAST tool is not run on all commits -- score normalized to 0
Details
- Warn: 0 commits out of 14 are checked with a SAST tool
Reason
19 existing vulnerabilities detected
Details
- Warn: Project is vulnerable to: GHSA-67hx-6x53-jw92
- Warn: Project is vulnerable to: GHSA-qwcr-r2fm-qrc7
- Warn: Project is vulnerable to: GHSA-grv7-fg5c-xmjg
- Warn: Project is vulnerable to: GHSA-pxg6-pf52-xh8x
- Warn: Project is vulnerable to: GHSA-h452-7996-h45h
- Warn: Project is vulnerable to: GHSA-3xgq-45jj-v275
- Warn: Project is vulnerable to: GHSA-rv95-896h-c2vc
- Warn: Project is vulnerable to: GHSA-qw6h-vgh9-j6wx
- Warn: Project is vulnerable to: GHSA-9c47-m6qq-7p4h
- Warn: Project is vulnerable to: GHSA-952p-6rrq-rcjv
- Warn: Project is vulnerable to: GHSA-9wv6-86v2-598j
- Warn: Project is vulnerable to: GHSA-hrpp-h998-j3pp
- Warn: Project is vulnerable to: GHSA-c2qf-rxjj-qqgw
- Warn: Project is vulnerable to: GHSA-m6fv-jmcg-4jfg
- Warn: Project is vulnerable to: GHSA-cm22-4g7w-348p
- Warn: Project is vulnerable to: GHSA-f5x3-32g6-xq36
- Warn: Project is vulnerable to: GHSA-72xf-g2v4-qvf3
- Warn: Project is vulnerable to: GHSA-j8xg-fqg3-53r7
- Warn: Project is vulnerable to: GHSA-3h5v-q93c-6h6q
Score
3.9
/10
Last Scanned on 2024-11-18
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 MoreOther packages similar to @tg-resources/superagent
superagent
elegant & feature rich browser / node HTTP with a fluent API
@types/superagent
TypeScript definitions for superagent
supertest
SuperAgent driven library for testing HTTP servers
@tg-resources/core
Abstractions on-top of `superagent` (or other Ajax libaries) for communication with REST.