Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: add helper methods to ParseFileTransferable protocol #411

Merged
merged 2 commits into from
Sep 13, 2022
Merged

feat: add helper methods to ParseFileTransferable protocol #411

merged 2 commits into from
Sep 13, 2022

Conversation

cbaker6
Copy link
Contributor

@cbaker6 cbaker6 commented Sep 13, 2022

New Pull Request Checklist

Issue Description

#410 added the ParseFileTransferable protocol which allows developers to upload ParseFile's directly to different file storage mediums as oppose to uploading to a Parse Server. In order for developers to take advantage of the ParseFileTransferable protocol, they have to understand the response type a Parse Server will send and structure the response of the uploaded file accordingly.

If the Swift SDK provided a set of helper methods, it would remove the developer needing to understand server and client responses and ease the process.

Related issue: #n/a

Approach

Add the following helper methods: makeSuccessfulUploadResponse() and makeDummyUploadTask()

/**
     Compose a valid file upload response with a name and url.
     
     Use this method after uploading a file to any file storage to
     respond to the Swift SDK upload request.
     - parameter name: The name of the file.
     - parameter url: The url of the file that was stored.
     - returns: A tuple of `(Data, HTTPURLResponse?)` where `Data` is the
     JSON encoded file upload response and `HTTPURLResponse` is the metadata
     associated with the response to the load request.
     */
    func makeSuccessfulUploadResponse(_ name: String, url: URL) throws -> (Data, HTTPURLResponse?)

    /**
     Compose a dummy upload task.
     
     Use this method if you do not need the Parse Swift SDK to start
     your upload task for you.
     - returns: A dummy upload task that starts an upload of zero bytes
     to localhost.
     - throws: An error of type `ParseError`.
     */
    func makeDummyUploadTask() throws -> URLSessionUploadTask

Example

// Initialize the Swift SDK with your class
ParseSwift.initialize(configuration: .init(applicationId: "applicationId",
                               clientKey: "clientKey",
                               masterKey: "masterKey",
                               serverURL: url,
                               parseFileTransfer: MyFileTransferAdapter())) // Pass an instance of your conforming adapter

// Defined in some other file
class MyFileTransferAdapter: ParseFileTransferable {

        func upload(with request: URLRequest,
                    from bodyData: Data?,
                    completion: @escaping (Data?, URLResponse?, URLRequest?, Error?) -> Void) throws -> URLSessionUploadTask {
            try storageUpload(completion: completion)
        }

        func upload(with request: URLRequest,
                    fromFile fileURL: URL,
                    // swiftlint:disable:next line_length
                    completion: @escaping (Data?, URLResponse?, URLRequest?, Error?) -> Void) throws -> URLSessionUploadTask {
            try storageUpload(completion: completion)
        }

        func storageUpload(completion: @escaping (Data?,
                                               URLResponse?,
                                               URLRequest?,
                                               Error?) -> Void) throws -> URLSessionUploadTask {

            // Dispatch is only here to simulate some delay, this would be the upload to your preferred storage
            DispatchQueue.main.asyncAfter(deadline: .now() + 3) {
                do {
                   // Use the new helper method to create a proper response for your uploaded file name and url
                   let response = try makeSuccessfulUploadResponse(name, url: url)
                   completion(response.0, response.1, nil, nil)
                } catch {
                   completion(nil, nil, nil, error)
                }
                
            }
            // If you don't have a URLSessionUploadTask, use the new dummy method to create a fake one and return it.
            return try makeDummyUploadTask()
        }
}

TODOs before merging

  • Fix a small bug where some url responses that threw errors were being cached
  • Add tests
  • Add entry to changelog
  • Add changes to documentation (guides, repository pages, in-code descriptions)

@parse-github-assistant
Copy link

parse-github-assistant bot commented Sep 13, 2022

Thanks for opening this pull request!

  • 🎉 We are excited about your hands-on contribution!

@codecov
Copy link

codecov bot commented Sep 13, 2022

Codecov Report

Base: 89.96% // Head: 89.98% // Increases project coverage by +0.02% 🎉

Coverage data is based on head (f739b77) compared to base (9ab5271).
Patch coverage: 96.61% of modified lines in pull request are covered.

Additional details and impacted files
@@            Coverage Diff             @@
##             main     #411      +/-   ##
==========================================
+ Coverage   89.96%   89.98%   +0.02%     
==========================================
  Files         159      159              
  Lines       15286    15323      +37     
==========================================
+ Hits        13752    13789      +37     
  Misses       1534     1534              
Impacted Files Coverage Δ
Sources/ParseSwift/API/Responses.swift 95.00% <ø> (ø)
...s/ParseSwift/Protocols/ParseFileTransferable.swift 96.00% <95.65%> (-4.00%) ⬇️
Sources/ParseSwift/Extensions/URLSession.swift 82.14% <97.22%> (+1.22%) ⬆️
Sources/ParseSwift/Objects/ParseUser.swift 87.09% <0.00%> (-0.18%) ⬇️
Sources/ParseSwift/API/API+Command.swift 89.61% <0.00%> (+0.20%) ⬆️
Sources/ParseSwift/Types/ParseFile.swift 89.41% <0.00%> (+0.68%) ⬆️

Help us with your feedback. Take ten seconds to tell us how you rate us. Have a feature suggestion? Share it here.

☔ View full report at Codecov.
📢 Do you have feedback about the report comment? Let us know in this issue.

@cbaker6 cbaker6 merged commit e2827c5 into parse-community:main Sep 13, 2022
@cbaker6 cbaker6 deleted the fileUpdates branch September 13, 2022 22:20
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant