From 1ed3cf8318b253aa1734324566112cd3a03bbdbe Mon Sep 17 00:00:00 2001 From: pavanpodila Date: Tue, 26 Mar 2024 12:34:38 +0530 Subject: [PATCH] chore: Update default API version to current date dynamically 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. --- packages/sanity/sanity_client/lib/client.dart | 18 +++++++++++++++--- 1 file changed, 15 insertions(+), 3 deletions(-) diff --git a/packages/sanity/sanity_client/lib/client.dart b/packages/sanity/sanity_client/lib/client.dart index 2ff4f36e..fb5e6797 100644 --- a/packages/sanity/sanity_client/lib/client.dart +++ b/packages/sanity/sanity_client/lib/client.dart @@ -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, @@ -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.'); } } @@ -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 fetch(Uri uri) async { final response = await httpClient.get(uri, headers: _requestHeaders);