Skip to content
Repos

DevPlaceApp

Markdown 9.6 KB122 lines Opens in site

Directory Raw Download

Data layer interface (for UI code)

Namespace dp, includes relative to src/. Threading: every callback and every state mutation runs on the SDL main thread (UiQueue::drain() in the main loop). A cancelled call (token->cancel()) never calls back. Calls that fail before any network (no token) call back asynchronously via UiQueue.

template <class T> using Done = std::function<void(Result<T>)>;   // api/ApiTypes.hpp
// Result<T>: ok(), value(), error().   Result<Unit> = "void" result.   CancelPtr = shared_ptr<CancelToken>
struct Error { enum class Kind { Offline, Timeout, Http, Api, Decode, Cancelled, Unauthorized, Local } kind;
               int status; std::string message; bool isSpecific; };

Show an error: AlertMessage a = AlertMessage::presentedError(error); (core/AlertMessage.hpp: fields isPresented, title, message, buttonText; none(), presentedError(const std::string&), presentedError(const Error&), presentedMessage(const std::string&)). Cancelled gives no alert; API-class errors with status and a non-specific message show "(status) message".

Picking the implementation

DevPlaceApi& api = useMock ? static_cast<DevPlaceApi&>(MockDevPlaceApi::shared())   // api/mock/MockDevPlaceApi.hpp
                           : static_cast<DevPlaceApi&>(ProdDevPlaceApi::shared());  // api/ProdDevPlaceApi.hpp

NetworkService::instance().start() must have run for the prod API. MockDevPlaceApi::setDelayScale(double) (0 = fast).

api/DevPlaceApi.hpp (abstract, every method returns CancelPtr)

using Str = std::optional<std::string>;

logIn(email, password, Done<Unit>)                       // sets AppState token and currentUser
signUp(username, email, password, confirmPassword, const BirthDate&, bool acceptTerms, Done<Unit>)
deleteAccount(password, Done<Unit>)
feed(const std::optional<Date>& before, Done<Feed>)       feed(Done<Feed>)                 // first page
postDetail(slug, Done<PostDetail>)
createPost(Str title, optional<PostTopic>, content, vector<UploadResponse> attachments, Str pollQuestion,
           vector<string> pollOptions, Str projectLink, Done<Unit>)
editPost(slug, title, PostTopic, content, projectLink, Done<Unit>)       deletePost(slug, Done<Unit>)
createComment(TargetType, targetId, content, Str parentId, vector<UploadResponse>, Done<Unit>)
editComment(uid, content, Done<Unit>)                    deleteComment(uid, Done<Unit>)
profile(Str username, Done<Profile>)                     // nullopt = own profile (needs token)
followUser / unfollowUser / blockUser / unblockUser / muteUser / unmuteUser (username, Done<Unit>)
messages(Str withUid, Done<MessagesInbox>)               messages(Done<MessagesInbox>)
sendMessage(receiverId, content, vector<UploadResponse>, Done<Unit>)
unique_ptr<MessagesSocket> makeMessagesSocket(otherUserId)
usersForMentioning(query, Done<UserSearch>)
notifications(const optional<Date>& before, Done<Notifications>)   notifications(Done<Notifications>)
openNotification(uid, Done<NotificationOpen>)            notificationCounts(Done<NotificationCounts>)
markNotificationRead(uid, Done<Unit>)                    markAllNotificationsRead(Done<Unit>)
registerPushDevice(deviceToken, Done<Unit>)              unregisterPushDevice(deviceToken, Done<Unit>)
vote(TargetType, targetId, Vote, Done<Unit>)             // backend toggles: always send Vote::Up to add/remove an upvote
submitPollChoice(pollId, optionId, Done<Unit>)           react(TargetType, targetId, emoji, Done<Unit>)
reportReasons(Done<vector<ReportReason>>)                report(TargetType, targetId, reason, Str detail, Done<Unit>)
uploadFile(const std::string& bytes, filename, mimeType, Done<UploadResponse>)
uploadFromUrl(url, Str filename, Done<UploadResponse>)   deleteAttachment(uid, Done<Unit>)
refreshTokenIfNeeded(Done<Unit>)                         // called internally before every authenticated request

Derived classes hide the convenience overloads: call them through a DevPlaceApi&, or add using DevPlaceApi::feed;. Limits to enforce in forms: spec/ModelLimits.hpp (kMaxPostTitleLength 500, kMinPostContentLength 10, kMaxPostContentLength 125000, kMinCommentContentLength 3, kMaxDirectMessageLength 2000, kMaxAttachmentsCount 10, kMaxPollOptionsCount 6, kMaxReportDetailLength 2000).

api/MessagesSocket.hpp

using EventHandler = std::function<void(const ChatSocketEvent&)>;   // UI thread
setEventHandler(EventHandler)  connect()  disconnect()  send(content, vector<string> attachmentUids, clientId)
sendTyping()  sendRead(withUid)

LiveMessagesSocket(receiverUid, UrlProvider) (api/LiveMessagesSocket.hpp), MockMessagesSocket (api/mock). Events: ChatSocketEvent{type: Ready|Message|Typing|Read|Failed|Disconnected, userUid, message (optional ChatSocketIncomingMessage), fromUid, byUid, clientId, text} (model/ChatSocketEvent.hpp). Codec: ChatSocketCodec::decode/encodeSend/encodeTyping/encodeRead. Reconnect: emits Disconnected, waits 200 ms doubling to 5000 ms, a fresh ticket per connect.

api/DevPlaceRequest.hpp (SDK port, one method per endpoint, explicit token)

Constructed with NetworkService& (default instance). Same Done<T> shape. Token = optional<AuthToken>. Auth: getAuthToken, signUp, forgotPassword, resetPassword. Feed: getFeed(tab, topic, search, before, token), getPost, createPost, editPost, deletePost. Comments: createComment, editComment, deleteComment. getProjects, getProject, getGists, getGist, getNews, getArticle, getProfile(username, tab, token), searchProfiles, deleteAccount, getFollowers, getFollowing, followUser, unfollowUser, blockUser, unblockUser, muteUser, unmuteUser, getLeaderboard, vote, submitPollChoice, react, toggleBookmark, getBookmarks, getReportReasons, report, getMessages, sendMessage, searchMessageRecipients, getMessagesWebSocketTicket, std::string messagesWebSocketUrl(ticket) const, getNotifications, openNotification, getNotificationCounts, markNotificationRead, markAllNotificationsRead, registerPushDevice, uploadFile (multipart), uploadFromUrl, deleteAttachment. ApiErrorDecoder::decodeBody(body) / fromResponse(status, body) (api/ApiErrorDecoder.hpp). DevPlaceError::notLoggedIn(), invalidUrl(s), postNotEditable() (api/DevPlaceError.hpp).

store/AppState.hpp (singleton AppState::instance(), extends Observable)

version() -> uint64 (grows on every mutation)    subscribe(std::function<void()>) -> id (0 = refused)    unsubscribe(id)
token() currentUser() feed() unreadNotificationCount() unreadMessageCount() pendingConversationUid()  (const optional<>& / int64)
isLoggedIn()  isCurrentUser(id)
setToken  setCurrentUser  setFeed  setUnreadCounts(notifications, messages)  setPendingConversationUid  clear()
loadFeed(DevPlaceApi&, Done<Unit>)               loadUnreadCounts(DevPlaceApi&, std::function<void()> done = {})
loadMoreFeed(DevPlaceApi&, Done<Unit>)           conversationUser(uid, DevPlaceApi&, function<void(optional<User>)>)
updatePostVoteInFeed(postId, Vote, count)        updateCommentVoteInFeed(commentId, Vote)
updatePostReactionInFeed(postId, emoji)          updateCommentReactionInFeed(commentId, emoji)
performVoteToggle(TargetType, targetId, Vote currentVote, DevPlaceApi&, function<void(Vote)> apply, function<void()> done = {})
performReactionToggle(TargetType, targetId, emoji, DevPlaceApi&, function<void()> apply, function<void()> done = {})

UI redraw rule: remember version() per frame, redraw when it changed (or subscribe).

store/SettingsStore.hpp (SettingsStore::instance(), extends Observable, file settings.json)

Getters: appearance() (AppearanceMode: System, Light, Dark; raw(), title(), default Dark), showFeedAttachments(), showFeedComments(), showReportButtons() (default true), recentEmojis() (max 30), draftPostTitle(), draftPostMessage(), draftReplyMessage(). Setters: setAppearance, setShowFeedAttachments, setShowFeedComments, setShowReportButtons, setDraftPostTitle, setDraftPostMessage, setDraftReplyMessage, recordEmojiPick(emoji). rebind(dir), reload().

store/SessionStore.hpp (SessionStore::instance(), extends Observable, file session.json, mode 0600)

email(), password() (optional<string>), setEmail(optional<string>), setPassword(optional<string>) (false when not persisted). Store the credentials after a successful login so refreshTokenIfNeeded can re-login; clear both on logout.

model/ (all static T fromJson(const Json&), throws DecodeError when a required key is missing/null/mistyped)

User, Attachment, UploadResponse, Media, Badge, Reactions (toggling), Comment (id(), voteCount(), replacingReactions, replacingChildren, applyingVote), CommentTree (updatingVote, updatingReaction), Poll, PollOption, Post (id(), replacingReactions, replacingRecentComments), PostDetail (with(...)), Feed (replacingPosts), Article, ArticleDetail, News, Gist, GistDetail, Gists, Project, ProjectDetail, Projects, Profile, Followers, Following, FollowUser, Leaderboard, LeaderboardEntry, Bookmarks, BookmarkItem, Conversation, Message, MessagesInbox, MessagesWebSocketTicket, UserSearch, Notifications, NotificationGroup, Notification, NotificationCounts, NotificationOpen, ReportReason, ActionResponse, AuthToken (isExpired(), willExpireSoon()), BirthDate (fromDate(Date), toString()), Vote (Up, Down, None; value()), PostTopic (all(), raw(), name(), fromRaw), TargetType, Role, NotificationType, PushProvider, AppearanceMode. Models are plain aggregates; Post::id() style helpers return the prefixed identity ("post:" + uid).

Core helpers

Timer::after(ms, fn) (core/Timer.hpp, UI thread, cancellable), Observable, Uuid::random(), AppPaths::prefDirectory().

273.8ms