-
-
Notifications
You must be signed in to change notification settings - Fork 82
Example for custom collection dispatchers #364
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from 4 commits
Commits
Show all changes
6 commits
Select commit
Hold shift + click to select a range
b5491e1
docs: add custom collection example
sij411 c08d367
refactor: add tagged posts dispatcher instead calling function directly
sij411 5fa09da
refactor: use setCollectionDispatcher
sij411 c2ee64a
refactor: use fetch
sij411 bf05e9d
fix: remove Create
sij411 7bbeb85
refactor: remove unused imports and inconsistent whitespaces, add com…
sij411 File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,12 @@ | ||
Custom Collections Example | ||
======================== | ||
|
||
This example demonstrates how to implement custom collections in Fedify. | ||
Custom collections allow you to define your own ActivityPub collections with | ||
custom logic for dispatching items and counting collection sizes. | ||
|
||
|
||
~~~~ sh | ||
deno task codegen # At very first time only | ||
deno run -A ./main.ts | ||
~~~~ |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,123 @@ | ||
import { Create, createFederation, MemoryKvStore, Note } from "@fedify/fedify"; | ||
|
||
// Mock data - in a real application, this would query your database | ||
const POSTS = [ | ||
new Create({ | ||
id: new URL("https://example.com/posts/post-1"), | ||
content: "ActivityPub is a decentralized social networking protocol...", | ||
tags: [ | ||
new URL("https://example.com/tags/ActivityPub"), | ||
new URL("https://example.com/tags/Decentralization"), | ||
], | ||
}), | ||
new Create({ | ||
id: new URL("https://example.com/posts/post-2"), | ||
content: "Fedify makes it easy to build federated applications...", | ||
}), | ||
|
||
new Create({ | ||
id: new URL("https://example.com/posts/post-3"), | ||
content: "WebFinger is a protocol for discovering information...", | ||
tags: [new URL("https://example.com/tags/ActivityPub")], | ||
}), | ||
|
||
new Create({ | ||
id: new URL("https://example.com/posts/post-4"), | ||
content: "HTTP Signatures provide authentication for ActivityPub...", | ||
}), | ||
|
||
new Create({ | ||
id: new URL("https://example.com/posts/post-5"), | ||
content: "Understanding ActivityPub's data model is crucial...", | ||
}), | ||
]; | ||
|
||
function getTagFromUrl(url: string): string { | ||
const parts = url.split("/"); | ||
return parts[parts.length - 1]; | ||
} | ||
|
||
function getTaggedPostsByTag(tag: string): Create[] { | ||
const results = POSTS.filter((post) => { | ||
if (!post.tagIds) { | ||
return false; | ||
} | ||
const postTags = post.tagIds; | ||
const matches = postTags.some((tagId) => { | ||
return getTagFromUrl(tagId.toString()) === tag; | ||
}); | ||
return matches; | ||
}); | ||
|
||
return results; | ||
} | ||
|
||
async function demonstrateCustomCollection() { | ||
// Note: federation instance created for demonstration | ||
const federation = createFederation<void>({ kv: new MemoryKvStore() }); | ||
|
||
federation.setCollectionDispatcher( | ||
"TaggedPosts", | ||
Note, | ||
"/users/{userId}/tags/{tag}", | ||
( | ||
_ctx: { url: URL }, | ||
values: Record<string, string>, | ||
cursor: string | null, | ||
) => { | ||
if (!values.userId || !values.tag) { | ||
throw new Error("Missing userId or tag in values"); | ||
} | ||
const posts = getTaggedPostsByTag(values.tag); | ||
sij411 marked this conversation as resolved.
Show resolved
Hide resolved
|
||
const items = posts.map((post) => (new Note({ | ||
id: new URL(`/posts/${post.id}`, _ctx.url), | ||
content: post.content, | ||
}))); | ||
sij411 marked this conversation as resolved.
Show resolved
Hide resolved
|
||
|
||
if (cursor != null) { | ||
const idx = Number.parseInt(cursor, 10); | ||
if (Number.isNaN(idx)) { | ||
sij411 marked this conversation as resolved.
Show resolved
Hide resolved
|
||
throw new Error("Invalid cursor"); | ||
sij411 marked this conversation as resolved.
Show resolved
Hide resolved
|
||
} | ||
return { | ||
items: [items[idx]], | ||
nextCursor: idx < items.length - 1 ? (idx + 1).toString() : null, | ||
prevCursor: idx > 0 ? (idx - 1).toString() : null, | ||
}; | ||
} | ||
return { items }; | ||
}, | ||
).setCounter(async (_ctx, values) => { | ||
// Return the total count of tagged posts | ||
const count = (await getTaggedPostsByTag(values.tag)).length; | ||
return count; | ||
}); | ||
|
||
const response = await federation.fetch( | ||
new Request( | ||
"https://example.com/users/someone/tags/ActivityPub", | ||
sij411 marked this conversation as resolved.
Show resolved
Hide resolved
|
||
{ | ||
headers: { | ||
Accept: "application/activity+json", | ||
}, | ||
}, | ||
), | ||
{ | ||
contextData: undefined, | ||
}, | ||
); | ||
|
||
console.log("Custom collection response status:", response.status); | ||
|
||
if (response.ok) { | ||
const jsonResponse = await response.json(); | ||
console.log("Custom collection data:", jsonResponse); | ||
} else { | ||
const errorText = await response.text(); | ||
console.log("Error response:", errorText); | ||
} | ||
sij411 marked this conversation as resolved.
Show resolved
Hide resolved
|
||
} | ||
|
||
if (import.meta.main) { | ||
demonstrateCustomCollection().catch(console.error); | ||
} |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.