addRemoteAsset method Null safety
Adds a remote asset to the repository. This will upload the asset to the
CMS, where it will be stored and resized. Returns a MediaAsset with
a persistent ID that can be used for future reference to the asset.
Returns null in case of failure.
The asset to be stored is referenced by a local device URL. The repository
does not assume ownership of the file, the caller needs to clean up if
the file is temporary.
Implementation
Future<MediaAsset?> addRemoteAsset(String url, MediaType mediaType) async {
const gqlQueryString = '''
mutation StoreNewAsset(\$file: Upload!) {
upload(file: \$file)
{
id
name
formats
url
}
}
''';
try {
const uuid = Uuid();
final byteData = await File(url).readAsBytes();
final multipartFile = MultipartFile.fromBytes(
byteData,
filename: '_zzzASSETzzz${uuid.v4()}',
contentType: MediaType('image', 'jpg'),
);
final queryResult = await graphQLClient.mutate<void>(MutationOptions(
document: gql(gqlQueryString),
// For some reason, dio's MultipartFile instance cannot be written to
// flutter_graphql's cache, even though gql_dio_link is able to serialize
// it for the request. Due to this we need to disable caching on image
// upload.
fetchPolicy: FetchPolicy.noCache,
variables: <String, dynamic>{
'file': multipartFile,
},
));
if (queryResult.hasException) {
logger?.e(queryResult.exception.toString());
return null;
}
final assetData = queryResult.data!['upload'] as Map<String, dynamic>;
if (assetData.isNotEmpty) {
final gqlAsset = MediaGqlEntity.fromJson(assetData);
if (gqlAsset == null) {
logger?.e('Unable to deserialize uploaded media asset');
return null;
}
return gqlAsset.toMediaAsset();
}
return null;
} catch (e, stackTrace) {
logger?.e('Could not add media asset to repository', e, stackTrace);
return null;
}
}