Skip to content

Commit

Permalink
chore: Update default API version to current date dynamically
Browse files Browse the repository at this point in the history
The commit dynamically updates the `defaultApiVersion` in Sanity's client configuration, calculated based on the current date. This modification is intended to ensure that the most relevant data is always fetched. Changes were also made to handle the case where no token is provided, removing the need for a hard assertion and setting the headers correspondingly.
  • Loading branch information
pavanpodila committed Mar 26, 2024
1 parent 2893cfb commit 1ed3cf8
Showing 1 changed file with 15 additions and 3 deletions.
18 changes: 15 additions & 3 deletions packages/sanity/sanity_client/lib/client.dart
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,16 @@ final class SanityConfig {
final Perspective perspective;
final bool explainQuery;

static const defaultApiVersion = 'v2021-10-21';
static final String defaultApiVersion = (() {
final today = DateTime.now();
final parts = [
today.year.toString(),
today.month.toString().padLeft(2, '0'),
today.day.toString().padLeft(2, '0')
].join('-');

return 'v$parts';
})();

SanityConfig({
required this.projectId,
Expand All @@ -29,7 +38,8 @@ final class SanityConfig {
this.apiVersion = apiVersion ?? defaultApiVersion,
this.perspective = perspective ?? Perspective.raw,
this.explainQuery = explainQuery ?? false {
assert(this.token.trim().isNotEmpty, 'Invalid Token provided');
assert(this.token.trim().isNotEmpty,
'Invalid Token provided. Setup an API token, with Viewer access, in the Sanity Management Console.');
}
}

Expand All @@ -46,7 +56,9 @@ class SanityClient {
final UrlBuilder? urlBuilder,
}) : httpClient = httpClient ?? http.Client(),
urlBuilder = urlBuilder ?? SanityUrlBuilder(config),
_requestHeaders = {'Authorization': 'Bearer ${config.token}'};
_requestHeaders = config.token != null
? {'Authorization': 'Bearer ${config.token}'}
: {};

Future<SanityQueryResponse> fetch(Uri uri) async {
final response = await httpClient.get(uri, headers: _requestHeaders);
Expand Down

0 comments on commit 1ed3cf8

Please sign in to comment.