Working follow and unfollow interactions for users

This commit is contained in:
2026-04-02 21:41:27 -04:00
parent f82bc223bb
commit 9c131b98a6
8 changed files with 713 additions and 8 deletions

View File

@@ -2,7 +2,7 @@
// Do not edit this file manually
import type { AshRpcError, ConditionalPaginatedResultMixed, InferResult, SortString, UUID, UnifiedFieldSelection, ValidationResult, mediaFilterInput, mediaResourceSchema, mediaSortField, tweetsFilterInput, tweetsResourceSchema, tweetsSortField, usersFilterInput, usersResourceSchema, usersSortField } from "./ash_types";
import type { AshRpcError, ConditionalPaginatedResultMixed, InferResult, SortString, UUID, UnifiedFieldSelection, ValidationResult, followsFilterInput, followsResourceSchema, followsSortField, mediaFilterInput, mediaResourceSchema, mediaSortField, tweetsFilterInput, tweetsResourceSchema, tweetsSortField, usersFilterInput, usersResourceSchema, usersSortField } from "./ash_types";
export type * from "./ash_types";
// Helper Functions
@@ -201,6 +201,245 @@ export async function executeValidationRpcRequest<T>(
export type FollowUserInput = {
followingId: UUID;
};
export type FollowUserFields = UnifiedFieldSelection<followsResourceSchema>[];
export type InferFollowUserResult<
Fields extends FollowUserFields | undefined,
> = InferResult<followsResourceSchema, Fields>;
export type FollowUserResult<Fields extends FollowUserFields | undefined = undefined> = | { success: true; data: InferFollowUserResult<Fields>; }
| { success: false; errors: AshRpcError[]; }
;
/**
* Create a new Follow
*
* @ashActionType :create
*/
export async function followUser<Fields extends FollowUserFields | undefined = undefined>(
config: {
tenant?: string;
input: FollowUserInput;
fields?: Fields;
headers?: Record<string, string>;
fetchOptions?: RequestInit;
customFetch?: (input: RequestInfo | URL, init?: RequestInit) => Promise<Response>;
}
): Promise<FollowUserResult<Fields extends undefined ? [] : Fields>> {
const payload = {
action: "follow_user",
...(config.tenant !== undefined && { tenant: config.tenant }),
input: config.input,
...(config.fields !== undefined && { fields: config.fields })
};
return executeActionRpcRequest<FollowUserResult<Fields extends undefined ? [] : Fields>>(
payload,
config
);
}
/**
* Validate: Create a new Follow
*
* @ashActionType :create
* @validation true
*/
export async function validateFollowUser(
config: {
tenant?: string;
input: FollowUserInput;
headers?: Record<string, string>;
fetchOptions?: RequestInit;
customFetch?: (input: RequestInfo | URL, init?: RequestInit) => Promise<Response>;
}
): Promise<ValidationResult> {
const payload = {
action: "follow_user",
...(config.tenant !== undefined && { tenant: config.tenant }),
input: config.input
};
return executeValidationRpcRequest<ValidationResult>(
payload,
config
);
}
export type ReadFollowFields = UnifiedFieldSelection<followsResourceSchema>[];
export type InferReadFollowResult<
Fields extends ReadFollowFields | undefined,
Page extends ReadFollowConfig["page"] = undefined
> = ConditionalPaginatedResultMixed<Page, Array<InferResult<followsResourceSchema, Fields>>, {
results: Array<InferResult<followsResourceSchema, Fields>>;
hasMore: boolean;
limit: number;
offset: number;
count?: number | null;
type: "offset";
}, {
results: Array<InferResult<followsResourceSchema, Fields>>;
hasMore: boolean;
limit: number;
after: string | null;
before: string | null;
previousPage: string;
nextPage: string;
count?: number | null;
type: "keyset";
}>;
export type ReadFollowConfig = {
tenant?: string;
fields: ReadFollowFields;
filter?: followsFilterInput;
sort?: SortString<followsSortField> | SortString<followsSortField>[];
page?: (
{
limit?: number;
offset?: number;
count?: boolean;
} | {
limit?: number;
after?: string;
before?: string;
}
);
headers?: Record<string, string>;
fetchOptions?: RequestInit;
customFetch?: (input: RequestInfo | URL, init?: RequestInit) => Promise<Response>;
};
export type ReadFollowResult<Fields extends ReadFollowFields, Page extends ReadFollowConfig["page"] = undefined> = | { success: true; data: InferReadFollowResult<Fields, Page>; }
| { success: false; errors: AshRpcError[]; }
;
/**
* Read Follow records
*
* @ashActionType :read
*/
export async function readFollow<Fields extends ReadFollowFields, Config extends ReadFollowConfig = ReadFollowConfig>(
config: Config & { fields: Fields }
): Promise<ReadFollowResult<Fields, Config["page"]>> {
const payload = {
action: "read_follow",
...(config.tenant !== undefined && { tenant: config.tenant }),
...(config.fields !== undefined && { fields: config.fields }),
...(config.filter && { filter: config.filter }),
...(config.sort && { sort: Array.isArray(config.sort) ? config.sort.join(",") : config.sort }),
...(config.page && { page: config.page })
};
return executeActionRpcRequest<ReadFollowResult<Fields, Config["page"]>>(
payload,
config
);
}
/**
* Validate: Read Follow records
*
* @ashActionType :read
* @validation true
*/
export async function validateReadFollow(
config: {
tenant?: string;
headers?: Record<string, string>;
fetchOptions?: RequestInit;
customFetch?: (input: RequestInfo | URL, init?: RequestInit) => Promise<Response>;
}
): Promise<ValidationResult> {
const payload = {
action: "read_follow",
...(config.tenant !== undefined && { tenant: config.tenant })
};
return executeValidationRpcRequest<ValidationResult>(
payload,
config
);
}
export type UnfollowUserInput = {
followingId: UUID;
};
export type InferUnfollowUserResult = {};
export type UnfollowUserResult = | { success: true; data: InferUnfollowUserResult; }
| { success: false; errors: AshRpcError[]; }
;
/**
* Execute generic action on Follow
*
* @ashActionType :action
*/
export async function unfollowUser(
config: {
tenant?: string;
input: UnfollowUserInput;
headers?: Record<string, string>;
fetchOptions?: RequestInit;
customFetch?: (input: RequestInfo | URL, init?: RequestInit) => Promise<Response>;
}
): Promise<UnfollowUserResult> {
const payload = {
action: "unfollow_user",
...(config.tenant !== undefined && { tenant: config.tenant }),
input: config.input
};
return executeActionRpcRequest<UnfollowUserResult>(
payload,
config
);
}
/**
* Validate: Execute generic action on Follow
*
* @ashActionType :action
* @validation true
*/
export async function validateUnfollowUser(
config: {
tenant?: string;
input: UnfollowUserInput;
headers?: Record<string, string>;
fetchOptions?: RequestInit;
customFetch?: (input: RequestInfo | URL, init?: RequestInit) => Promise<Response>;
}
): Promise<ValidationResult> {
const payload = {
action: "unfollow_user",
...(config.tenant !== undefined && { tenant: config.tenant }),
input: config.input
};
return executeValidationRpcRequest<ValidationResult>(
payload,
config
);
}
export type ReadUserFields = UnifiedFieldSelection<usersResourceSchema>[];

View File

@@ -6,12 +6,32 @@
export type UUID = string;
export type UtcDateTimeUsec = string;
// follows Schema
export type followsResourceSchema = {
__type: "Resource";
__primitiveFields: "id";
id: UUID;
};
export type followsAttributesOnlySchema = {
__type: "Resource";
__primitiveFields: "id";
id: UUID;
};
// users Schema
export type usersResourceSchema = {
__type: "Resource";
__primitiveFields: "id" | "email";
__primitiveFields: "id" | "email" | "followerCount" | "followingCount" | "amIFollowing" | "myFollowId";
id: UUID;
email: string;
followerCount: number;
followingCount: number;
amIFollowing: boolean;
myFollowId: UUID;
};
@@ -78,6 +98,20 @@ export type tweetsAttributesOnlySchema = {
};
export type followsFilterInput = {
and?: Array<followsFilterInput>;
or?: Array<followsFilterInput>;
not?: Array<followsFilterInput>;
id?: {
eq?: UUID;
notEq?: UUID;
in?: Array<UUID>;
};
};
export type usersFilterInput = {
and?: Array<usersFilterInput>;
or?: Array<usersFilterInput>;
@@ -95,6 +129,40 @@ export type usersFilterInput = {
in?: Array<string>;
};
followerCount?: {
eq?: number;
notEq?: number;
greaterThan?: number;
greaterThanOrEqual?: number;
lessThan?: number;
lessThanOrEqual?: number;
in?: Array<number>;
isNil?: boolean;
};
followingCount?: {
eq?: number;
notEq?: number;
greaterThan?: number;
greaterThanOrEqual?: number;
lessThan?: number;
lessThanOrEqual?: number;
in?: Array<number>;
isNil?: boolean;
};
amIFollowing?: {
eq?: boolean;
notEq?: boolean;
isNil?: boolean;
};
myFollowId?: {
eq?: UUID;
notEq?: UUID;
in?: Array<UUID>;
isNil?: boolean;
};
};
@@ -203,7 +271,10 @@ export type tweetsFilterInput = {
};
export const usersFilterFields = ["id", "email"] as const;
export const followsFilterFields = ["id"] as const;
export type followsFilterField = (typeof followsFilterFields)[number];
export const usersFilterFields = ["id", "email", "followerCount", "followingCount", "amIFollowing", "myFollowId"] as const;
export type usersFilterField = (typeof usersFilterFields)[number];
export const mediaFilterFields = ["id", "s3Key", "userId", "tweetId", "user", "tweet"] as const;
@@ -213,7 +284,10 @@ export const tweetsFilterFields = ["id", "content", "likes", "userId", "inserted
export type tweetsFilterField = (typeof tweetsFilterFields)[number];
export const usersSortFields = ["id", "email"] as const;
export const followsSortFields = ["id"] as const;
export type followsSortField = (typeof followsSortFields)[number];
export const usersSortFields = ["id", "email", "followerCount", "followingCount", "amIFollowing", "myFollowId"] as const;
export type usersSortField = (typeof usersSortFields)[number];
export const mediaSortFields = ["id", "s3Key", "userId", "tweetId"] as const;

View File

@@ -16,6 +16,8 @@ import {
unlikeTweet,
updateTweet,
readUser,
followUser,
unfollowUser,
buildCSRFHeaders,
} from "./ash_rpc";
import { uploadFile } from "./upload";
@@ -26,7 +28,14 @@ const queryClient = new QueryClient({
// ── Types ──────────────────────────────────────────────────────────────────────
type User = { id: string; email: string };
type User = {
id: string;
email: string;
followerCount?: number;
followingCount?: number;
amIFollowing?: boolean;
myFollowId?: string | null;
};
type MediaItem = { id: string; s3Key: string };
type Tweet = {
id: string;
@@ -887,6 +896,56 @@ function RefreshButton() {
);
}
function FollowButton({ targetUserId, amIFollowing }: { targetUserId: string; amIFollowing: boolean }) {
const { userId: currentUserId } = useContext(AuthCtx);
const qc = useQueryClient();
const followMutation = useMutation({
mutationFn: async () => {
const res = await followUser({
input: { followingId: targetUserId },
headers: buildCSRFHeaders(),
});
if (!res.success) throw new Error((res.errors?.[0] as any)?.message ?? "Follow failed");
},
onSuccess: () => {
qc.invalidateQueries({ queryKey: ["users"] });
qc.invalidateQueries({ queryKey: ["user", targetUserId] });
},
});
const unfollowMutation = useMutation({
mutationFn: async () => {
const res = await unfollowUser({
input: { followingId: targetUserId },
headers: buildCSRFHeaders(),
});
if (!res.success) throw new Error((res.errors?.[0] as any)?.message ?? "Unfollow failed");
},
onSuccess: () => {
qc.invalidateQueries({ queryKey: ["users"] });
qc.invalidateQueries({ queryKey: ["user", targetUserId] });
},
});
if (!currentUserId || currentUserId === targetUserId) return null;
const isPending = followMutation.isPending || unfollowMutation.isPending;
return (
<button
className={`mx-action-btn${amIFollowing ? " mx-action-btn--active" : ""}`}
disabled={isPending}
onClick={(e) => {
e.stopPropagation();
amIFollowing ? unfollowMutation.mutate() : followMutation.mutate();
}}
>
{isPending ? "..." : amIFollowing ? "Unfollow" : "Follow"}
</button>
);
}
function UserCard({ user }: { user: User }) {
const [ctxMenu, setCtxMenu] = useState<{ x: number; y: number } | null>(null);
@@ -913,7 +972,14 @@ function UserCard({ user }: { user: User }) {
<div className="mx-tweet-body">
<div className="mx-tweet-header">
<span className="mx-tweet-handle">{user.email}</span>
<FollowButton targetUserId={user.id} amIFollowing={user.amIFollowing ?? false} />
</div>
{(user.followerCount !== undefined || user.followingCount !== undefined) && (
<div className="mx-tweet-meta" style={{ fontSize: "0.8rem", color: "var(--mx-muted)", marginTop: "4px" }}>
<span>{user.followerCount ?? 0} followers</span>
<span style={{ marginLeft: "12px" }}>{user.followingCount ?? 0} following</span>
</div>
)}
</div>
{ctxMenu && (
<ContextMenu
@@ -932,7 +998,7 @@ function UserList() {
queryKey: ["users"],
queryFn: async () => {
const res = await readUser({
fields: ["id", "email"],
fields: ["id", "email", "followerCount", "followingCount", "amIFollowing"],
headers: buildCSRFHeaders(),
});
if (!res.success) throw new Error("Failed to load users");
@@ -970,7 +1036,7 @@ function UserDetail({ userId }: { userId: string }) {
queryKey: ["user", userId],
queryFn: async () => {
const res = await readUser({
fields: ["id", "email"],
fields: ["id", "email", "followerCount", "followingCount", "amIFollowing"],
filter: { id: { eq: userId } },
headers: buildCSRFHeaders(),
});
@@ -998,7 +1064,16 @@ function UserDetail({ userId }: { userId: string }) {
<div className="mx-tweet-avatar">
<span>M</span>
</div>
<span className="mx-tweet-handle">{user.email}</span>
<div>
<div style={{ display: "flex", alignItems: "center", gap: "12px" }}>
<span className="mx-tweet-handle">{user.email}</span>
<FollowButton targetUserId={user.id} amIFollowing={user.amIFollowing ?? false} />
</div>
<div style={{ fontSize: "0.85rem", color: "var(--mx-muted)", marginTop: "6px", display: "flex", gap: "16px" }}>
<span><strong>{user.followerCount ?? 0}</strong> followers</span>
<span><strong>{user.followingCount ?? 0}</strong> following</span>
</div>
</div>
</div>
</div>
</div>