-
Notifications
You must be signed in to change notification settings - Fork 14
Using Custom Requests
Arun Prakash edited this page May 7, 2024
·
3 revisions
Dive into wordpress_client to streamline CRUD operations effortlessly! Here's a quick guide in five simple steps:
Request classes handle data sent to the server. Extend IRequest
and use the build()
method to set the request URL and HTTP method.
π Example:
import 'dart:async';
import 'package:wordpress_client/wordpress_client.dart';
final class MyRequest extends IRequest {
MyRequest({
this.context,
this.page = 1,
this.perPage = 10,
super.cancelToken,
super.authorization,
super.events,
super.receiveTimeout,
super.requireAuth = false,
super.sendTimeout,
super.validator,
super.extra,
super.headers,
super.queryParameters,
});
RequestContext? context;
int page = 1;
int perPage = 10;
String? search;
@override
FutureOr<WordpressRequest> build(Uri baseUrl) {
final queryParameters = <String, String>{}
..addIfNotNull('context', context?.name)
..addIfNotNull('page', page)
..addIfNotNull('per_page', perPage)
..addAllIfNotNull(this.queryParameters)
..addAllIfNotNull(extra);
return WordpressRequest(
url: RequestUrl.absoluteMerge(
Uri(path: 'wp-json/custom_path/my_path/my_endpoint'),
baseUrl,
),
queryParameters: queryParameters,
method: HttpMethod.get,
cancelToken: cancelToken,
events: events,
requireAuth: requireAuth,
authorization: authorization,
validator: validator,
sendTimeout: sendTimeout,
receiveTimeout: receiveTimeout,
);
}
}
Interfaces in WordpressClient
link callers to internal operations. Inherit from IRequestInterface
and use mixins for instant request capabilities.
π Example:
import 'package:wordpress_client/wordpress_client.dart';
import 'my_request.dart';
import 'my_response.dart';
final class MyInterface extends IRequestInterface
with ListOperation<MyResponse, MyRequest> {}
Unveil your crafted interface to wordpress_client. Here's how:
π Code:
client.register<MyInterface, MyResponse>(
interface: MyInterface(),
decoder: MyResponse.fromJson,
encoder: (instance) => (instance as MyResponse).toJson(),
key: 'my_interface',
overriteIfTypeExists: true,
);
π¨ Note: Some keys like me
, posts
, and others belong exclusively to wordpress_client. Be cautious when using them.
Once your interface is set, it's time to send requests effortlessly!
π Example:
final myInterface = client.get<MyInterface>('my_interface');
final response = await myInterface.list(
MyRequest(
context: RequestContext.view,
),
);
switch (response) {
case WordpressSuccessResponse():
final data = response.data;
break;
case WordpressFailureResponse():
final error = response.error;
break;
}
That's it! For more examples, check out the links below:
- π Post Interface
- π List Post
- π Post Response