forked from cauios/cau_study_by_cauios
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPostApi.swift
More file actions
83 lines (66 loc) · 2.79 KB
/
PostApi.swift
File metadata and controls
83 lines (66 loc) · 2.79 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
//
// PostApi.swift
// cau_study_ios
//
// Created by Davee on 2018. 4. 22..
// Copyright © 2018년 신형재. All rights reserved.
//
// [Dahye's comment] This class will only care about post
import Foundation
import FirebaseDatabase
class PostApi {
var REF_POSTS = Database.database().reference().child("posts")
// [Dahye's comment] This method will listen to events at the locations of all posts on the DB
// in the closure, we'll recieve data snapshot which contains post data.
func observePosts(completion: @escaping (Post) -> Void) {
REF_POSTS.observe(.childAdded) { (snapshot: DataSnapshot) in
if let dict = snapshot.value as? [String: Any] {
let newPost = Post.transformPost(dicr: dict, key: snapshot.key)
completion(newPost)
}
}
}
// [Dahye's comment] This method uses the input 'post id' to look up the location of all posts for the child nodes corresponding that post id.
// [Dahye 0723]
func observePost(withId id: String, completion: @escaping (Post) -> Void){
REF_POSTS.child(id).observeSingleEvent(of: DataEventType.value, with: {
snapshot in
if let dict = snapshot.value as? [String: Any] {
let post = Post.transformPost(dicr: dict, key: snapshot.key)
completion(post)
}
})
}
func observeMyPosts(withId id: String, completion: @escaping (Post)-> Void) {
REF_POSTS.child(id).observeSingleEvent(of: .value, with: {snapshot in
if let dict = snapshot.value as? [String: Any] {
let post = Post.transformPost(dicr: dict, key: snapshot.key)
completion(post)
}
})
}
func observeSaved(withId id: String, completion: @escaping (Post)-> Void) {
REF_POSTS.child(id).observeSingleEvent(of: .value, with: {snapshot in
if let dict = snapshot.value as? [String: Any] {
let post = Post.transformPost(dicr: dict, key: snapshot.key)
completion(post)
}
})
}
func deletePost(postId id: String, onSuccess: @escaping () -> Void, onError: @escaping(_ errorMessage: String?) -> Void) {
Api.Post.REF_POSTS.child(id).removeValue(completionBlock: {(err,ref) in
if err != nil {
return
}
onSuccess()
})
}
func deleteMyPost(postId id: String, userId uid: String, onSuccess: @escaping () -> Void, onError: @escaping(_ errorMessage: String?) -> Void) {
Api.MyPosts.REF_MYPOSTS.child(uid).child(id).removeValue(completionBlock: {(err,ref) in
if err != nil {
return
}
onSuccess()
})
}
}