Skip to content

Commit

Permalink
getMessages types: Handle Message being PmMessage | StreamMessage.
Browse files Browse the repository at this point in the history
In the same basic way as in the previous commit, but with a bit of
added complexity: the function isn't `(Message) => Message`; it's
`(ServerMessage) => Message`.

So, start by expressing how `ServerMessage` relates to `Message`, in
a way that applies uniformly to `PmMessage` and `StreamMessage`.

Then, annotate the function's param by applying that expression to
`M`, which is a subtype of `Message`, and leave the return value as
`M`.

See discussion at
  https://chat.zulip.org/#narrow/stream/243-mobile-team/topic/.60PmMessage.60.2C.20.60StreamMessage.60.20types.3F/near/1126688.
  • Loading branch information
chrisbobbe committed Mar 5, 2021
1 parent 5c008bc commit 68c6742
Showing 1 changed file with 12 additions and 6 deletions.
18 changes: 12 additions & 6 deletions src/api/messages/getMessages.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
import type { Auth, ApiResponseSuccess } from '../transportTypes';
import type { Identity } from '../../types';
import type { Message, ApiNarrow } from '../apiTypes';
import type { Reaction, UserId } from '../modelTypes';
import type { PmMessage, StreamMessage, Reaction, UserId } from '../modelTypes';
import { apiGet } from '../apiFetch';
import { identityOfAuth } from '../../account/accountMisc';
import { AvatarURL } from '../../utils/avatar';
Expand Down Expand Up @@ -31,11 +31,15 @@ export type ServerReaction = $ReadOnly<{|
|}>,
|}>;

export type ServerMessage = $ReadOnly<{|
...$Exact<Message>,
// How `ServerMessage` relates to `Message`, in a way that applies
// uniformly to `Message`'s subtypes.
type ServerMessageOf<M: Message> = {|
...$Exact<M>,
avatar_url: string | null,
reactions: $ReadOnlyArray<ServerReaction>,
|}>;
|};

export type ServerMessage = ServerMessageOf<PmMessage> | ServerMessageOf<StreamMessage>;

// The actual response from the server. We convert the data from this to
// `ApiResponseMessages` before returning it to application code.
Expand All @@ -49,8 +53,10 @@ export const migrateMessages = (
messages: $ReadOnlyArray<ServerMessage>,
identity: Identity,
): Message[] =>
messages.map(message => ({
...message,
messages.map(<M: Message>(message: ServerMessageOf<M>): M => ({
// (This casting looks unnecessary, but seems to nudge Flow in the
// right direction.)
...(message: ServerMessageOf<M>),
avatar_url: AvatarURL.fromUserOrBotData({
rawAvatarUrl: message.avatar_url,
email: message.sender_email,
Expand Down

0 comments on commit 68c6742

Please sign in to comment.