Giter Club home page Giter Club logo

crud-vapor-app's Introduction

Crud-Vapor-App

iOS CRUD App using Vapor API

Technologies

  • SwiftUi

Demo

  • Create product, Update product quantity, Delete product
products.mp4

Create

  • Http Client
func sendData<T: Codable>(url: URL, object: T, httpMeyhod: String) async throws {
        var request = URLRequest(url: url)
        
        //tell the request what kind of data we locking for
        request.httpMethod = httpMeyhod
        request.addValue(MIMEType.JSON.rawValue,
                         forHTTPHeaderField: HttpHeaders.contebtType.rawValue)
        
        request.httpBody = try? JSONEncoder().encode(object)
        
        let(_, response) = try await URLSession.shared.data(for: request)
        guard (response as? HTTPURLResponse)?.statusCode == 300 else {
            throw HttpError.badResponse
        }
    }
    
  • View Model

     let product = Product(id: nil, name: productName, actual_price: actualPrice,
     profit_price: profitPrice, work_price: workPrice,  quantity: Quintity)
         try await HttpClient.shared.sendData(url: url, object: product,
                                              httpMeyhod: HttpMethodes.POST.rawValue)

Read

  • Http Client
        func fetch<T: Codable>(url: URL) async throws -> [T] {
        let (data, response) = try await URLSession.shared.data(from: url)
        
        guard (response as? HTTPURLResponse)?.statusCode == 200 else {
            throw HttpError.badResponse
        }
        
        guard let object = try? JSONDecoder().decode([T].self, from: data) else{
            throw HttpError.errorDecodingData
        }
        
        return object
    }
    
  • View Model
         let productResponse: [Product] = try await HttpClient.shared.fetch(url: url)
         DispatchQueue.main.async {
             self.products = productResponse
         }

Update

  • Http Client
    fetch func
  • View Model
     let productToUpdate = Product(id: productID, name: productName, actual_price: actualPrice, 
     profit_price: profitPrice, work_price: workPrice,  quantity: Quintity)
         try await HttpClient.shared.sendData(url: url, object: productToUpdate,
                                              httpMeyhod: HttpMethodes.PUT.rawValue)
    
                                              

Delete

  • Http Client
    delete func will take the product id
   func delete(at id: UUID, url: URL) async throws {
        
        //new url request object
        var request = URLRequest(url: url)
        // set the methode to delete
        request.httpMethod = HttpMethodes.DELETE.rawValue
        // use the new url data and give it the request
        // let(_, response)the _ because we dont need to get data just a response
        let(_, response) = try await URLSession.shared.data(for: request)
        
        
        // get the response and cast it as an http url response then check if the status code is equal to 200
        // else if this doesnt work throw a bad response error
        guard (response as? HTTPURLResponse)?.statusCode == 200 else {
            throw HttpError.badResponse
        }
    }
    
    
  • View Model

In the ViewModel, iterate over the list of product id and pass the one that matches to delete func.

// delete the product from the database
     offesets.forEach { i in
         guard let productId = products[i].id else {
             return
         }
         guard let url = URL(string: Constants.baseURL + Endpoints.products
          + "/\(productId)") else {
             return
         }
         Task {
             do {
                 try await HttpClient.shared.delete(at: productId, url: url)
             } catch {
                 print("Error: \(error)")
             }
         }
     } 
     // delet the product from the Product array in the view
     products.remove(atOffsets: offesets)
}

crud-vapor-app's People

Contributors

gyda13 avatar

Stargazers

 avatar  avatar  avatar

Watchers

 avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.