Skip to content

No deserialization found for type Uri? #426

Closed

Description

@yahu1031

I tried uploading a file to serverpod_cloud_storage. It works fine. But when I try getting the public url, I ran into this exception.

Debugger traces

args: {
  "path" : "PhotoViewer.m",
  "auth" : "1:P4OpgPmsZ289mQnWII0cET17c5tW0CnJ",
  "method" : "getDownloadUrl"
}

e: FormatException (FormatException: No deserialization found for type Uri?)

endpoint: "assets"

method: "getDownloadUrl"

Endpoint code

import 'package:serverpod/serverpod.dart';

class AssetsEndpoint extends Endpoint {
  Future<String?> getUploadDescription(Session session, String path) async {
    try {
      session.log('Path: $path');
      return session.storage.createDirectFileUploadDescription(
        storageId: 'public',
        path: path,
      );
    } on Exception catch (e) {
      session.log(e.toString(), level: LogLevel.error);
      return null;
    }
  }

  Future<bool> verifyUpload(Session session, String path) async {
    return await session.storage.verifyDirectFileUpload(
      storageId: 'public',
      path: path,
    );
  }

  Future<Uri?> getDownloadUrl(Session session, String path) async {
    session.log('Path: $path');
    return session.storage.getPublicUrl(
      storageId: 'public',
      path: path,
    );
  }
}

I use in flutter code

uploading
? const CircularProgressIndicator.adaptive()
: ElevatedButton(
    onPressed: () async {
      FilePickerResult? result =
          await FilePicker.platform.pickFiles(
        allowMultiple: false,
      );
      String? uploadDescription;
      if (result != null) {
        setState(() {
          uploading = true;
        });
        var name = result.files.single.name;
        uploadDescription = await AppConstants.client.assets
            .getUploadDescription(name);
        var bytes =
            File(result.files.single.path!).readAsBytesSync();
        bool success = false;
        if (uploadDescription != null) {
          var uploader = FileUploader(uploadDescription);
          var a = ByteData.sublistView(bytes);
          success = await uploader.uploadByteData(a);
          var uploaded =
              await AppConstants.client.assets.verifyUpload(name);
          var exists = await AppConstants.client.assets
              .checkFileExists(name);
          print('Uploaded: $uploaded');
          print('Exists: $exists');
          if (exists) {
            var a = await AppConstants.client.assets
                .getDownloadUrl(result.files.single.name);
            print(a?.toString());
            await Fluttertoast.showToast(
              msg: '$uploadDescription  $success',
              toastLength: Toast.LENGTH_SHORT,
              gravity: ToastGravity.BOTTOM,
              timeInSecForIosWeb: 5,
              backgroundColor:
                  success ? Colors.green : Colors.red,
              textColor: Colors.white,
              fontSize: 16.0,
            );
          }
          setState(() {
            uploading = false;
          });
        }
      }
    },
    child: const Text('Upload and get URL'),
  ),

serverpod_cloud_storage table

id storageId path addedTime expiration byteData verified
1 public PhotoViewer.m 2022-12-03 21:39:10.476641 NULL BINARY (13 KB) TRUE

Activity

  1. yahu1031 commented on Dec 3, 2022

    @yahu1031
    ContributorAuthor

    UPDATE: Fix Found in serverpod_serialization/lib/src/serialization.dart

    /// Deserialize the provided JSON [data] to an object of type [t] or [T].
    T deserialize<T>(dynamic data, [Type? t]) {
      t ??= T;
      if (t == int || t == getType<int?>()) {
        return data;
      }
    
      ... 
    
      else if (t == getType<ByteData?>()) {
        return (data as String?)?.base64DecodedByteData() as T;
      } 
      /// --------------------------ADD THIS--------------------------
      /// Try parsing the Url to Uri
      else if (t == Uri || t == getType<Uri?>()) {
        /// This condition is optional(Can be considered)
        if(data == null) {
          return null as T;
        }
        return Uri.tryParse(data ?? '') as T;
      } 
      /// --------------------------TILL HERE-------------------------
      throw FormatException('No deserialization found for type $t');
    }
    
    /// Deserialize the provided JSON [data] by using the className stored in the [data].
    dynamic deserializeByClassName(Map<String, dynamic> data) {
      var className = data['className'];
      switch (className) {
        case 'int':
          return deserialize<int>(data['data']);
        ...
    
        /// --------------------------ADD THIS--------------------------
        /// Add Uri case too
        case 'Uri':
          return deserialize<Uri>(data['data']);
        /// --------------------------TILL HERE-------------------------
      }
      throw FormatException('No deserialization found for type named $className');
    }
  2. vlidholt commented on Dec 7, 2022

    @vlidholt
    Collaborator

    Uri is currently not supported by the serialization layer. This would be a great future feature though.

  3. added
    enhancement
    on Dec 7, 2022
  4. yahu1031 commented on Dec 7, 2022

    @yahu1031
    ContributorAuthor

    @vlidholt So should I make a PR with this fix?

  5. vlidholt commented on Dec 7, 2022

    @vlidholt
    Collaborator

    It also needs tests and correct serialization for the database.

  6. realkhalife commented on Dec 12, 2022

    @realkhalife

    Anytime i try to use session.db.query i still got the same error FormatException: No deserialization found for type dynamic

  7. realkhalife commented on Dec 14, 2022

    @realkhalife

    @yahu1031 can you help me out ?

  8. yahu1031 commented on Dec 14, 2022

    @yahu1031
    ContributorAuthor

    @realkhalife sure but that need to be changed in framework level and that won't work on deployment. Cause serverpod(changed code) doesn't exist there in server.

  9. realkhalife commented on Dec 14, 2022

    @realkhalife

    i see, thank you. can't wait for the fix in future upgrades

  10. II11II commented on Dec 17, 2022

    @II11II
    Contributor

    Ill create PR for this, after the PR #493 is going to be merged

  11. yahu1031 commented on Dec 18, 2022

    @yahu1031
    ContributorAuthor

    @II11II also check out the solution I gave. 😇

  12. II11II commented on Dec 18, 2022

    @II11II
    Contributor

    Yes sure

  13. vlidholt commented on Dec 18, 2022

    @vlidholt
    Collaborator

    Ill create PR for this, after the PR #493 is going to be merged

    Very cool. I think after doing the Duration one, this should be straight forward. :)

  14. yahu1031 commented on Dec 19, 2022

    @yahu1031
    ContributorAuthor

    @II11II If you want me to create one, I can do it.

  15. II11II commented on Dec 19, 2022

    @II11II
    Contributor

    @yahu1031 I do not mind)
    Please confirm, when you start creating pr

  16. 1 remaining item

  17. yahu1031 commented on Dec 19, 2022

    @yahu1031
    ContributorAuthor

    @II11II Done created one 😄

  18. mozexty commented on Mar 14, 2023

    @mozexty

    I updated Serverpod from 1.0.0 to 1.0.1. Then every new endpoint I write gives me this error, even if the returned class contains a single String.

    FormatException: No deserialization found for type dynamic #0 SerializationManager.deserialize (package:serverpod_serialization/src/serialization.dart:77:5) #1 Protocol.deserialize (package:nusape_server/src/generated/protocol.dart:456:18) #2 EndpointDispatch._formatArg (package:serverpod/src/server/endpoint_dispatch.dart:163:33) #3 EndpointDispatch.handleUriCall (package:serverpod/src/server/endpoint_dispatch.dart:106:25) <asynchronous suspension> #4 Server._handleRequest (package:serverpod/src/server/server.dart:224:18) <asynchronous suspension>

    Old endpoints are working correctly.

    I checked #536 , #237 , #498.

  19. fischerscode commented on Mar 14, 2023

    @fischerscode
    Contributor

    The methods in your endpoint must explicitly return a Future<String> (add it in front of your method name).

    After a serverpod generate, it should work.
    If it doesn't, please create a new issue and include an example.

  20. mozexty commented on Mar 14, 2023

    @mozexty

    Yes it works. But I need to return an object with many fields.
    Is returning Future<String> a temporary solution?
    My other endpoints are returning Serverpod-generated classes successfully.

  21. added
    area: storage
    on Sep 2, 2024
  22. added
    area: endpoints
    and removed
    area: storage
    on Dec 17, 2024
  23. moved this from Next 🌟 to Now 🔥 in Serverpod Frameworkson Jan 27, 2025
  24. assigned and unassigned on Jan 28, 2025
  25. moved this from Now 🔥 to Done 🚀 in Serverpod Frameworkson Jan 29, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

area: endpointsenhancement

Type

No type

Projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions