Coder Social home page Coder Social logo

vb10 / vexana Goto Github PK

View Code? Open in Web Editor NEW
141.0 8.0 38.0 6.61 MB

Vexana is network manager project with dio.

Home Page: https://pub.dev/packages/vexana

License: MIT License

Kotlin 0.09% Swift 1.00% Objective-C 0.03% Dart 66.99% Ruby 1.90% HTML 1.06% CMake 12.83% C++ 14.79% C 1.01% Shell 0.30%
flutter dio network

vexana's Introduction

Pub Pub Star on Github License: MIT Youtube: HardwareAndro Medium: Vbacik

vexana

Vexana is easy to use network process with dio. You can do dynamic model parsing, base error model, timeout and many utility functions.

Vexana-Game

Getting Started 🔥

Let's talk about usage details. You can learn more detail about vexana in test folder. Please check it out before using this package. I'm not good to write a readme 😅

Network Manager 😎

Have a lot of options: baseurl, logger, interceptors, base model etc.

If you want to manage your error model, you just declare your model so it's way getting the error model everywhere.

INetworkManager  networkManager = NetworkManage<Null or UserErrorModel>(isEnableLogger: true, errorModel: UserErrorModel(),
 options: BaseOptions(baseUrl: "https://jsonplaceholder.typicode.com/"));

Model Parse ⚔️

First, you have to provide the parse model, then the result model. (Result model could be a list, model or primitive)

final response =
await networkManager.send<Todo, List<Todo>>("/todos", parseModel: Todo(), method: RequestType.GET);

Base Headers 📍

You could be add key values to your every request directly.(add authentication key)

networkManager.addBaseHeader(MapEntry(HttpHeaders.authorizationHeader, response.data?.first.title ?? ''));
// Clear single header
networkManager.removeHeader('\${response.data?.first.id}');
// Clear all header
networkManager.clearHeader();

Download File 📍

Download File Simple

You can download any file format like pdf, png or etc with progress indicator.

final response = await networkManager.downloadFileSimple('http://www.africau.edu/images/default/sample.pdf', (count, total) {
      print('${count}');
});

//Example: Image.memory(response.data)

Download File

You can download by specifying model and request type.

final response = await networkManager.downloadFile(
    'financial-report',
    (count, total) {
      print('${count}');
    },
    method: RequestType.POST,
    data: FileDownloadModel(),
);

HTTP Post Request with Request Body 🚀

The model found in the request body must extend the abstract class INetworkModel, as follows.

class TodoPostRequestData extends INetworkModel<TodoPostRequestData>

Then, since the model will have toJson and fromJson properties, you can create the object and pass it directly to the send method.

So, it is sufficient to send only the request body object into the send method. You don't need to use toJson.

final todoPostRequestBody = TodoPostRequestData();
final response =
await networkManager.send<Todo, List<Todo>>("/todosPost", parseModel: Todo(), method: RequestType.POST, data: todoPostRequestBody);

Cancel Request

You can implement cancel token when need to invoke your request during to complete.

  final cancelToken = CancelToken();
    networkManager
        .send<ReqResModel, ReqResModel>('/users?delay=5',
            parseModel: ReqResModel(), method: RequestType.GET, canceltoken: cancelToken)
        .catchError((err) {
      if (CancelToken.isCancel(err)) {
        print('Request canceled! ' + err.message);
      }
    });

    cancelToken.cancel('canceled');

    await Future.delayed(const Duration(seconds: 8));

Primitive Request 🌼

Sometimes we need to parse only primitive types for instance List, String, int etc. You can use this method.

//
[
  "en",
  "tr",
  "fr"
]
//
networkManager.sendPrimitive<List>("languages");

Network Model 🛒

You must wrap your model with INetworkModel so that, we understand model has toJson and fromJson methods.

class Todo extends INetworkModel<Todo>

Refresh Token ♻️

Many projects use authentication structure for mobile security (like a jwt). It could need to renew an older token when the token expires. This time provided a refresh token option, we can lock all requests until the token refresh process is complete.

Since i locked all requests, I am giving a new service instance.

INetworkManager  networkManager = NetworkManager(isEnableLogger: true, options: BaseOptions(baseUrl: "https://jsonplaceholder.typicode.com/"),
onRefreshFail: () {  //Navigate to login },
 onRefreshToken: (error, newService) async {
    <!-- Write your refresh token business -->
    <!-- Then update error.req.headers to new token -->
    return error;
});

Caching 🧲

You need to write a response model in the mobile device cache sometimes. It's here now. You can say expiration date and lay back 🙏

    await networkManager.send<Todo, List<Todo>>("/todos",
        parseModel: Todo(),
        expiration: Duration(seconds: 3),
        method: RequestType.GET);

You must declare a caching type. It has FileCache and SharedCache options now. NetworkManager(fileManager: LocalFile()); If you want more implementation details about the cache, you should read this article

Without Network connection 🧲

Especially, mobile device many times lost connection for many reasons so if you want to retry your request, you need to add this code and that's it. Your app user can be show bottom sheet dialog and they will be use this features only tree times because i added this rule.

    // First you must be initialize your context with NoNetwork class
    networkManager = NetworkManager(
      isEnableLogger: true,
      noNetwork: NoNetwork(context),
      options: BaseOptions(baseUrl: 'https://jsonplaceholder.typicode.com'),

      errorModelFromData: _errorModelFromData, //This is optional.
    );

    // If you want to create custom widget, you can add in no network class with callback function.
      networkManager = NetworkManager(
      isEnableLogger: true,
      noNetwork: NoNetwork(
        context,
        customNoNetwork: (onRetry) {
          // You have to call this retry method your custom widget
          return NoNetworkSample(onPressed: onRetry);
        },
      ),
      options: BaseOptions(baseUrl: 'https://jsonplaceholder.typicode.com'),

      //Example request
       final response = await networkManager.send<Post, List<Post>>('/posts',
        parseModel: Post(), method: RequestType.GET, isErrorDialog: true);

And result!!

alt

Error model handle

This point so important for many apps. Some business operation want to show any message or logic when user did a mistake like wrong password etc. You can manage very easily to error model for whole project with this usage.

INetworkManager  networkManager = NetworkManage<UserErrorModel>(isEnableLogger: true, errorModel: UserErrorModel(),
 options: BaseOptions(baseUrl: "https://jsonplaceholder.typicode.com/"));

 IResponseModel<List<Post>?, BaseErrorModel?> response =  networkManager.send<Post, List<Post>>('/posts',
        parseModel: Post(), method: RequestType.GET);
      <!-- Error.model came from your backend with your declaration -->
      showDialog(response.error?.model?.message)

Tasks


  • Example project
  • Unit Test with json place holder
  • Unit Test with custom api
  • Handle network problem
  • Make a unit test all layers(%70).
  • Cache Option
    • Hive Support
    • Web Cache Support
  • Refresh Token Architecture
  • Usage Utility
  • Readme Update

License

License

2020 created for @VB10

Youtube Channel


Youtube

Contributors

Made with contrib.rocks.

EARTHQUAKE 7.8 and 7.6 6Feb2023

help

Turkey has recently been struck by a devastating earthquake with a magnitude of 7.8. The impact has been widespread and many communities have been severely affected. In this difficult time, we are reaching out to ask for your support. Any donation, no matter how small, will help us provide much-needed aid to those affected by the earthquake. Your generosity will help provide shelter, food, and medical supplies to those in need. Your contribution will make a real difference in the lives of those affected by this disaster. Thank you for your kindness and support.

You can donate for AHBAP with this site AHBAP_DONATE

vexana's People

Contributors

ahm3tcelik avatar ahmetmelihserter avatar alperen23230 avatar aydemiromer avatar basakk6 avatar behzodfaiziev avatar berksartik avatar burakjs avatar e-mre avatar mehmetkaranlik avatar mfurkanyuceal avatar vb10 avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

vexana's Issues

In-Memory Caching for Responses

Vexana already includes caching via local caching mechanism, i believe either we can improve this to in-memory caching for fast read/write access and safety issues. Or we can add another caching options while retaining the current one.

Update connectivity_plus dependency

Hello,
I am going to update connectivity_plus package which solves some issues in newer version. However, since it also dependes on version 2.3.5, I cound not update it.

Can I send a PR to update version of connectivity_plus to latest vesrion in vexana?

Thank you!

Type 'Uint8List' not found

Selamlar,
downloadFileSimple isimli function bir anda hata vermeye başladı sebebi ne olabilir anlamadım.

Screenshot at Jul 28 23-42-15

NoNetwork ile ilgili context sorunu

Merhaba hocam saygılar öncelikle. Architecture serinizle paralel bir şekilde kendimi geliştirmek için yazdığım bir uygulamada internetin kesildiği zamanda gösterilecek Popup vb durumları entegre etmeye çalışıyorum. Bir kaç yöntem denedim connectivity_plus kütüphanesini eklemeye çalıştığım zaman Vexana ile birlikte kullanıldığında hata meydana geliyor. Başka bir yöntem olarak vexana'nın sağladığı Nonetwork yapısını kullanmaya çalıştım .Vexana_manager.dart dosyasında(Architecture serisindeki) nonetwork'un istediği context'i sağlayamıyorum yardımcı olursanız sevinirim.

How to append to NetworkManager httpclient setting for skipping SSL sertificate check

Sometimes when we test network request on localhost and we don't have SSL sertificate, so we can not use Dio requests, because it shows status code 301, but on real site with SSL it works perfectly.

Here is default code:

NetworkManager({
    required BaseOptions options,
    bool? isEnableLogger,
    InterceptorsWrapper? interceptor,
    this.errorModel,
  }) {
    this.options = options;
    _addLoggerInterceptor(isEnableLogger ?? false);
    _addNetworkIntercaptors(interceptor);
    //TODO: Http adapter has come
    httpClientAdapter = DefaultHttpClientAdapter();
  }

I need to add next code to settings for turning off SSL checking and prevent error:

(httpClientAdapter as DefaultHttpClientAdapter).onHttpClientCreate = (HttpClient client) {
      client.badCertificateCallback = (X509Certificate cert, String host, int port) => true;
      return client;
    };

I found next solution on DIO package and it works perfectly, but I don't know how to insert this code to upper code:

var _dio = Dio();
    (_dio.httpClientAdapter as DefaultHttpClientAdapter).onHttpClientCreate = (HttpClient client) {
      client.badCertificateCallback = (X509Certificate cert, String host, int port) => true;
      return client;
    };
dio.send(...)

Please help me

how do we retryRequest

For example, if I don't have an internet connection and when the connection comes, how can I renew the request without missing it?

INetworkModel const constructor

There is nothing preventing INetworkModel abstract class to have const constructor but its not implemented. So any child class extends can't have const constructor. I suggest we add const constructor to INetworkModel. @VB10

How can i upload files with Vexana?

Hello!

How can i upload files with Vexana?

I added files in FormData. You can check my code in the picture.

image

But it gives this error.

image

I did do something wrong?

Somebody can help me?

Thanks and regards.
Gürhan Genç

Need to more unit test

We're plannig to testable library for a ci operation. If anyone send a pr it will work automaticly. You can follow this procces with this issue. @MehmetKaranlik

Windows Web Platform Dio Desteği

Windows web ortamın'da DIO desteği bulunmuyor. Dio için web ortamına desteklenmesinin yararlı olabileceğini düşünüyorum.

DioError [DioErrorType.DEFAULT]: Unsupported operation: Platform._version

How to fetch list of primitive types?

Response from the API is only a list of primitive types which looks like this.
[
"a",
"b",
"c",
"d",
]
How can I fetch this with Vexana? (response is just a list of string. It doesn`t have names or curly braces)

Bloc Eğitimi İçeriğinde kullanılan vexana hk.

Future<IResponseModel<TokenModel?>?> login(LoginModel model) async {
return await networkManager.send<TokenModel, TokenModel>(
'api/login',
data: model,
parseModel: TokenModel(),
method: RequestType.POST,
);
}

Kullanımında The type 'IResponseModel' is declared with 2 type parameters, but 1 type arguments were given.
Try adjusting the number of type arguments to match the number of type parameters kızmaktadır.

Cache Mekanizması Neye Göre Çalışıyor?

Selamlar,
Vexana paketini kullanmaya yeni başladım. getProductByCategoryId isminde backend metodum var. Gönderdiğim kategoriId değerine göre ürünlerimi döndürüyor. urlSuffix değeri duruma göre örneğin 1 veya 2 gidiyor. Bu tarz durumda cache mekanizması neye göre çalışıyor. Yaptığım testlere göre her zaman ilk attığım isteği cacheliyor. Örneğin urlSuffix değerini 2 gönderdiğimde yine urlSuffix = 1 isteğinin cache değerini döndürmekte. Yalnızca urlSuffix değil, queryParameters ve data ile attığımızda da aynı şekilde. Vexana'nın bu tarz bir desteği var mı? @VB10

final response = await networkService.manager
    .send<ProductModel, ProductModel>(
  NetworkRoutesConstants.getProductByCategoryId.uri,
  parseModel: ProductModel(),
  expiration: const Duration(minutes: 5),
  urlSuffix: id.toString(),
  method: RequestType.GET,
);

final response = await networkService.manager
    .send<ProductModel, ProductModel>(
  NetworkRoutesConstants.getProductByCategoryId.uri,
  parseModel: ProductModel(),
  expiration: const Duration(minutes: 5),
  queryParameters: {"Id" : id.toString()},
  method: RequestType.GET,
);

final response = await networkService.manager
    .send<ProductModel, ProductModel>(
  NetworkRoutesConstants.getProductByCategoryId.uri,
  parseModel: ProductModel(),
  expiration: const Duration(minutes: 5),
  data: {"Id" : id.toString()},
  method: RequestType.GET,
);

Vexana Cache return Statuss success data null

cache
Tek request'de datayı cache'leyebiliyorum. ama aynı anda iki farklı function'da cacheleme işlemi yapamıyorum. kullanıcı bilgilerini ve postlarını cachelemek istediğim de postların statuss'ü success dönüyor ama içi boş oluyor. tek bir bilgiyi cachelemek istersem sorunsuz çalışıyor.

Getting response.error.model null for Response Code 400

Hi,
I'm using this library since one year in our product.
And just noticed that in vexana: 3.3.2, I'm getting response.error.model as a null for status code 400.

I can see the response in the interceptor but not getting into the error model.

Please help, How can I get error model?

Refresh Token Problem

  • Refresh token retryCount variable can't initialized.
  • When refreshToken operation is success in networkWrapper, handler passes an error. And after that there's a model decode error. Because when we pass error in handler in success case, trying to decode error model. But we have a success refresh token model.

I fixed issues in this PR:
#13

Bearer Token ekleme

Vexana kullanımında slpash ve login sayfaları haricinde servise token göndermek istiyorum. Nasıl yapabilirim?

Local tanımlı baseurl ile çalışma

Vexana kullanarak oluşturulan bir yapıda baseUrl özelliğine localde tutulan bir string url verildiğinde url görülmemektedir ve ekteki hata oluşmaktadır.

Kullanımı :

INetworkManager networkManager = NetworkManager(
isEnableLogger: true,
options: BaseOptions(
baseUrl: LocaleManager.instance
.getStringValue(PreferencesKeys.SERVICE_URL)));

image

201 HTTP status code body parsing bug

When I make HTTP request and the process finish successfully API returns 201 as HTTP status code but response data becomes null, error data includes success response.

Screenshot from 2021-07-29 18-10-03

Parsing of EmptyParseModel throws error if response.body contains List

 final response = await manager.send<EmptyModel, EmptyModel>(
        APIConst.example,
        parseModel: EmptyModel(),
        method: RequestType.POST,
        data: example.toJson(),
      );

Partially Working Case

Response type: Map<String,dynamic>

Expected result:

response.data = EmptyModel(name: "anydata");

Actual result:

response.data = EmptyModel(name: null); // it doesn't give name, but at least data is not null

Not Working Case

Response type: List<Map<String,dynamic>>

Expected result:

response.data = EmptyModel(name: "anydata");

Actual result:

response.data = null;

It throws an error:
Parse Error: type 'List<EmptyModel>' is not a subtype of type 'EmptyModel' in type cast - response body: [{example: 1}] T model: EmptyParseModel , R model: EmptyParseModel

What is next:

I found a solution but I need to make sure that it works. After a while I am going to create PR if I succesfully test it

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.