Skip to content

Instantly share code, notes, and snippets.

@swdyh
Created November 16, 2023 07:24
Show Gist options
  • Save swdyh/cafd29d4eefa2da858757ad5d1911cef to your computer and use it in GitHub Desktop.
Save swdyh/cafd29d4eefa2da858757ad5d1911cef to your computer and use it in GitHub Desktop.
quiet intternet dart client
import 'dart:convert' as convert;
import 'dart:io' as io;
Future<void> main() async {
final apiKey = io.Platform.environment['QUIET_INTERNET_API_KEY']!;
final client = QuietInternetClient(apiKey: apiKey);
final posts = await client.getPosts(perPage: 1, visibility: 'ANYONE');
for (final post in posts) {
final postDetail = await client.getPost(post.slug);
print([
post.slug,
post.visibility,
post.title,
post.bodyMarkdown,
post.createdAt,
postDetail.bodyMarkdown,
]);
}
}
class QuietInternetClient {
static const endpoint = 'https://sizu.me/api';
final String apiKey;
QuietInternetClient({required this.apiKey});
Future<Iterable<Post>> getPosts({
int? page,
int? perPage,
String? sort,
String? direction,
String? visibility,
}) async {
final queryMap = <String, dynamic>{
if (page != null) 'page': '$page',
if (perPage != null) 'perPage': '$perPage',
if (sort != null) 'sort': sort,
if (direction != null) 'direction': direction,
if (visibility != null) 'visibility': visibility,
};
final query = Uri(queryParameters: queryMap);
final json = await _getJson('/v1/posts?${query}');
final post = json['posts'] as List? ?? [];
return List<Map<String, dynamic>>.from(post).map(Post.fromJson);
}
Future<Post> getPost(String slug) async {
final json = await _getJson('/v1/posts/$slug');
return Post.fromJson(json['post']);
}
Future<Map<String, dynamic>> _getJson(String path) async {
final httpClient = io.HttpClient();
final request = await httpClient.getUrl(Uri.parse('${endpoint}${path}'));
request.headers.add(io.HttpHeaders.authorizationHeader, 'Bearer $apiKey');
final response = await request.close();
if (response.statusCode != 200) {
throw Exception('Failed to get $path: ${response.statusCode}');
}
final body = await response.transform(convert.utf8.decoder).join();
httpClient.close();
return convert.json.decode(body);
}
}
class PostsResponse {
final List<Post> posts;
PostsResponse(this.posts);
}
class Post {
final String slug;
final String title;
final String? bodyMarkdown;
final String? bodyHtml;
final String? visibility;
final DateTime createdAt;
final DateTime updatedAt;
Post({
required this.slug,
required this.title,
required this.bodyMarkdown,
required this.bodyHtml,
required this.visibility,
required this.createdAt,
required this.updatedAt,
});
factory Post.fromJson(Map<String, dynamic> json) {
return Post(
slug: json['slug'],
title: json['title'],
bodyMarkdown: json['bodyMarkdown'],
bodyHtml: json['bodyHtml'],
visibility: json['visibility'],
createdAt: DateTime.parse(json['createdAt']),
updatedAt: DateTime.parse(json['updatedAt']),
);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment