Skip to content

Commit

Permalink
feat: remove flutter dependency (breaking change) (#58)
Browse files Browse the repository at this point in the history
  • Loading branch information
Youn authored Mar 22, 2022
1 parent 1f669f9 commit 6e4a610
Show file tree
Hide file tree
Showing 7 changed files with 110 additions and 60 deletions.
13 changes: 13 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -39,3 +39,16 @@
## 3.3.0

- feat: adding json, body to GET requests

## 4.0.0-nullsafety.0

- feat: migrate to null-safety

## 4.1.0

- enhancement: fix typos
- fix: revert cast to FutureOr<http.StreamedResponse>
- feat: migrate shared_preferences to stash_hive
- feat: update dependencies
- feat: remove flutter dependency
- feat: remove deprecated dependencies and field in the pubspec.yaml file
14 changes: 7 additions & 7 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
![banner-01](https://user-images.githubusercontent.com/1287098/68531964-ccead400-0320-11ea-93a6-fa83b9183dd8.png)


a flutter library to make HTTP requests (inspired by python [requests](https://github.com/psf/requests) module). It comes with JSON support and a lightweight implementation to store cookies like a browser.
a dart library to make HTTP requests (inspired by python [requests](https://github.com/psf/requests) module). It comes with JSON support and a lightweight implementation to store cookies like a browser.

### Cookies, huh?
Server side cookies (via response header `SET-COOKIE`) are stored using the assistance of `shared_preferences`. Stored cookies will be send seamlessly on the next http requests you make to the same domain (simple implementation, similar to a web browser)
Server side cookies (via response header `SET-COOKIE`) are stored using the assistance of `stash_hive`. Stored cookies will be send seamlessly on the next http requests you make to the same domain (simple implementation, similar to a web browser)


## Install
Expand All @@ -13,7 +13,7 @@ Add this to your package's pubspec.yaml file:

```yaml
dependencies:
requests: ^4.0.0-nullsafety.0
requests: ^4.1.0
```
## Usage
Expand All @@ -32,7 +32,7 @@ String body = r.content();


### the `Response` object
just like in python's request module, the `Response` object has this functionallity
just like in python's request module, the `Response` object has this functionality

- `r.throwForStatus()` - will throw an exception if the response `statusCode` is not a great success.
- `r.raiseForStatus()` - same as `throwForStatus`
Expand All @@ -41,9 +41,9 @@ just like in python's request module, the `Response` object has this functionall
- `r.headers` - the response headers
- `r.success` - a boolean. `true` indicates that the request was a great success
- `r.hasError` - a boolean. `true` indicates that the request was not a great success
- `r.bytes()` - return the body in the respone as a list of bytes
- `r.content()` - return the body in the respone as a string
- `r.json()` - recodes the body in the respone and returns the result (dynamic type)
- `r.bytes()` - return the body in the response as a list of bytes
- `r.content()` - return the body in the response as a string
- `r.json()` - recodes the body in the response and returns the result (dynamic type)


### Optional Arguments
Expand Down
32 changes: 26 additions & 6 deletions analysis_options.yaml
Original file line number Diff line number Diff line change
@@ -1,14 +1,34 @@
# Defines a default set of lint rules enforced for
# projects at Google. For details and rationale,
# see https://github.com/dart-lang/pedantic#enabled-lints.
include: package:pedantic/analysis_options.yaml
# This file configures the static analysis results for your project (errors,
# warnings, and lints).
#
# This enables the 'recommended' set of lints from `package:lints`.
# This set helps identify many issues that may lead to problems when running
# or consuming Dart code, and enforces writing Dart using a single, idiomatic
# style and format.
#
# If you want a smaller set of lints you can change this to specify
# 'package:lints/core.yaml'. These are just the most critical lints
# (the recommended set includes the core lints).
# The core lints are also what is used by pub.dev for scoring packages.

include: package:lints/recommended.yaml

# Uncomment the following section to specify additional rules.

# For lint rules and documentation, see http://dart-lang.github.io/linter/lints.
# Uncomment to specify additional rules.
# linter:
# rules:
# - camel_case_types

# analyzer:
# exclude:
# - path/to/excluded/files/**

# For more information about the core and recommended set of lints, see
# https://dart.dev/go/core-lints

# For additional information about configuring this file, see
# https://dart.dev/guides/language/analysis-options

analyzer:
exclude:
- test/**
40 changes: 33 additions & 7 deletions lib/src/common.dart
Original file line number Diff line number Diff line change
@@ -1,25 +1,51 @@
import 'dart:io';
import 'dart:async';
import 'dart:convert';
import 'package:hex/hex.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:stash/stash_api.dart';
import 'package:stash_hive/stash_hive.dart';
import 'package:crypto/crypto.dart';

class Common {
const Common();

// Temporary directory
static final path = Directory.systemTemp.path;

// Creates a store
static final store = newHiveDefaultVaultStore(path: path);

// Creates a vault from the previously created store
static final vault = store.vault<String>(
name: 'cookieVault',
eventListenerMode: EventListenerMode.synchronous,
);

/// Add / Replace this [Vault] [value] for the specified [key].
///
/// * [key]: the key
/// * [value]: the value
static Future<void> storageSet(String key, String value) async {
var sharedPreferences = await SharedPreferences.getInstance();
await sharedPreferences.setString(key, value);
await vault.put(key, value);
}

/// Returns the stash value for the specified [key]
///
/// * [key]: the key
///
/// Returns a [String]
static Future<String?> storageGet(String key) async {
var sharedPreferences = await SharedPreferences.getInstance();
return sharedPreferences.getString(key);
return await vault.get(key);
}

/// Removes the mapping for a [key] from this [Vault] if it is present.
///
/// * [key]: key whose mapping is to be removed from the [Vault]
///
/// Returns `true` if the removal of the mapping for the specified [key] was successful.
static Future<bool> storageRemove(String key) async {
var sharedPreferences = await SharedPreferences.getInstance();
return await sharedPreferences.remove(key);
await vault.remove(key);
return !await vault.containsKey(key);
}

static bool equalsIgnoreCase(String? string1, String? string2) {
Expand Down
5 changes: 2 additions & 3 deletions lib/src/requests.dart
Original file line number Diff line number Diff line change
Expand Up @@ -319,7 +319,7 @@ class Requests {

if (uri.scheme != 'http' && uri.scheme != 'https') {
throw ArgumentError(
"invalid url, must start with 'http://' or 'https://' sheme (e.g. 'http://example.com')");
"invalid url, must start with 'http://' or 'https://' scheme (e.g. 'http://example.com')");
}

var hostname = getHostname(url);
Expand Down Expand Up @@ -406,8 +406,7 @@ class Requests {
var response = await future.timeout(Duration(seconds: timeoutSeconds));

if (response is http.StreamedResponse) {
response = await (http.Response.fromStream(response)
as FutureOr<http.StreamedResponse>);
response = await http.Response.fromStream(response);
}

return await _handleHttpResponse(hostname, response, persistCookies);
Expand Down
30 changes: 8 additions & 22 deletions pubspec.yaml
Original file line number Diff line number Diff line change
@@ -1,30 +1,16 @@
name: requests
description: a flutter library that helps with http requests and stored cookies
version: 4.0.0-nullsafety.0
version: 4.1.0
homepage: https://github.com/jossef/requests
authors:
- Jossef Harush <[email protected]>
- Rick Stanley <[email protected]>
- Martin <https://github.com/genesiscz>
- Frederik Pietzko <[email protected]>
- Rafael Carvalho Monteiro <[email protected]>
- eggate <https://github.com/eggate>
- Dane Mackier <https://github.com/FilledStacks>
- Anirudh S <https://github.com/anirudh24seven>
- Imdat Solak <[email protected]>
- obuhovsergai <https://github.com/obuhovsergai>
environment:
sdk: '>=2.12.0 <3.0.0'
sdk: '>=2.16.1 <3.0.0'
dependencies:
flutter:
sdk: flutter
crypto: ^3.0.1
hex: ^0.2.0
http: ^0.13.1
logging: ^1.0.1
shared_preferences: ^2.0.5
http: ^0.13.4
logging: ^1.0.2
stash: ^4.0.1
stash_hive : ^4.0.1
dev_dependencies:
flutter_test:
sdk: flutter
pedantic: ^1.11.0
test: ^1.0.0
lints: ^1.0.0
test: ^1.16.0
36 changes: 21 additions & 15 deletions test/requests_test.dart
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
import 'package:requests/requests.dart';
import 'package:requests/src/common.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:test/test.dart';

void _validateResponse(Response r) {
Expand All @@ -12,9 +11,6 @@ void _validateResponse(Response r) {
void main() {
group('A group of tests', () {
final String PLACEHOLDER_PROVIDER = 'https://reqres.in';
setUp(() {
SharedPreferences.setMockInitialValues({});
});

test('plain http get', () async {
var r = await Requests.get('https://google.com');
Expand All @@ -25,7 +21,8 @@ void main() {
});

test('plain http get with query parameters', () async {
var r = await Requests.get('https://google.com', queryParameters: {'id': 1, 'name': null});
var r = await Requests.get('https://google.com',
queryParameters: {'id': 1, 'name': null});
r.raiseForStatus();
dynamic body = r.content();
expect(body, isNotNull);
Expand All @@ -42,7 +39,8 @@ void main() {
});

test('plain http get with port 8080', () async {
var r = await Requests.get('http://portquiz.net:8080/', timeoutSeconds: 30);
var r =
await Requests.get('http://portquiz.net:8080/', timeoutSeconds: 30);
r.raiseForStatus();
});

Expand All @@ -61,7 +59,8 @@ void main() {
'userId': 10,
'id': 91,
'title': 'aut amet sed',
'body': 'libero voluptate eveniet aperiam sed\nsunt placeat suscipit molestias\nsimilique fugit nam natus\nexpedita consequatur consequatur dolores quia eos et placeat',
'body':
'libero voluptate eveniet aperiam sed\nsunt placeat suscipit molestias\nsimilique fugit nam natus\nexpedita consequatur consequatur dolores quia eos et placeat',
},
bodyEncoding: RequestBodyEncoding.FormURLEncoded);
r.raiseForStatus();
Expand All @@ -76,7 +75,8 @@ void main() {
'userId': 10,
'id': 91,
'title': 'aut amet sed',
'body': 'libero voluptate eveniet aperiam sed\nsunt placeat suscipit molestias\nsimilique fugit nam natus\nexpedita consequatur consequatur dolores quia eos et placeat',
'body':
'libero voluptate eveniet aperiam sed\nsunt placeat suscipit molestias\nsimilique fugit nam natus\nexpedita consequatur consequatur dolores quia eos et placeat',
}
]);
r.raiseForStatus();
Expand All @@ -99,7 +99,8 @@ void main() {
'userId': 10,
'id': 91,
'title': 'aut amet sed',
'body': 'libero voluptate eveniet aperiam sed\nsunt placeat suscipit molestias\nsimilique fugit nam natus\nexpedita consequatur consequatur dolores quia eos et placeat',
'body':
'libero voluptate eveniet aperiam sed\nsunt placeat suscipit molestias\nsimilique fugit nam natus\nexpedita consequatur consequatur dolores quia eos et placeat',
});
r.raiseForStatus();
dynamic body = r.json();
Expand All @@ -118,7 +119,8 @@ void main() {
'userId': 10,
'id': 91,
'title': 'aut amet sed',
'body': 'libero voluptate eveniet aperiam sed\nsunt placeat suscipit molestias\nsimilique fugit nam natus\nexpedita consequatur consequatur dolores quia eos et placeat',
'body':
'libero voluptate eveniet aperiam sed\nsunt placeat suscipit molestias\nsimilique fugit nam natus\nexpedita consequatur consequatur dolores quia eos et placeat',
});
r.raiseForStatus();
dynamic body = r.json();
Expand Down Expand Up @@ -149,7 +151,8 @@ void main() {
});

test('response as Response object', () async {
var r = await Requests.post('$PLACEHOLDER_PROVIDER/api/users', body: {'name': 'morpheus'});
var r = await Requests.post('$PLACEHOLDER_PROVIDER/api/users',
body: {'name': 'morpheus'});
r.raiseForStatus();
var content = r.content();
var json = r.json();
Expand All @@ -172,7 +175,8 @@ void main() {

test('throw if both json and body used', () async {
try {
await Requests.post('$PLACEHOLDER_PROVIDER/api/unknown/23', body: {}, json: {});
await Requests.post('$PLACEHOLDER_PROVIDER/api/unknown/23',
body: {}, json: {});
} on ArgumentError catch (_) {
return;
}
Expand All @@ -197,15 +201,17 @@ void main() {

test('cookie parsing', () async {
var headers = Map<String, String>();
var cookiesString = '_ga=GA1.4..1563550573; ; ; ; data=1=2=3=4; textsize=NaN; tp_state=true; _ga=GA1.3..1563550573; __browsiUID=03b1cb22-d18d-&{"bt":"Browser","os":"Windows","osv":"10.0","m":"Desktop|Emulator","v":"Unknown","b":"Chrome","p":2}; _cb_ls=1; _cb=CaBNIWCf-db-3i9ro; _chartbeat2=..414141414.1..1; AMUUID=%; _fbp=fb.2..; adblockerfound=true';
var cookiesString =
'_ga=GA1.4..1563550573; ; ; ; data=1=2=3=4; textsize=NaN; tp_state=true; _ga=GA1.3..1563550573; __browsiUID=03b1cb22-d18d-&{"bt":"Browser","os":"Windows","osv":"10.0","m":"Desktop|Emulator","v":"Unknown","b":"Chrome","p":2}; _cb_ls=1; _cb=CaBNIWCf-db-3i9ro; _chartbeat2=..414141414.1..1; AMUUID=%; _fbp=fb.2..; adblockerfound=true';
headers['set-cookie'] = cookiesString;
var cookies = await Requests.extractResponseCookies(headers);

expect(cookies['_ga'], "GA1.3..1563550573");
expect(cookies['adblockerfound'], "true");
expect(cookies['textsize'], "NaN");
expect(cookies['data'], "1=2=3=4");
expect(cookies['__browsiUID'], '03b1cb22-d18d-&{"bt":"Browser","os":"Windows","osv":"10.0","m":"Desktop|Emulator","v":"Unknown","b":"Chrome","p":2}');
expect(cookies['__browsiUID'],
'03b1cb22-d18d-&{"bt":"Browser","os":"Windows","osv":"10.0","m":"Desktop|Emulator","v":"Unknown","b":"Chrome","p":2}');
});

test('string split', () async {
Expand All @@ -220,7 +226,7 @@ void main() {
});

test('from json', () async {
expect(Common.fromJson('{"a":1}'), {"a":1});
expect(Common.fromJson('{"a":1}'), {"a": 1});
expect(Common.fromJson(null), null);
});
});
Expand Down

0 comments on commit 6e4a610

Please sign in to comment.