Skip to content

Commit

Permalink
initial update redis cache comment counts
Browse files Browse the repository at this point in the history
  • Loading branch information
kabeaty committed Aug 1, 2023
1 parent 2e7424f commit 99fcf9d
Show file tree
Hide file tree
Showing 12 changed files with 69 additions and 10 deletions.
10 changes: 8 additions & 2 deletions src/core/client/count/injectJSONPCallback.ts
Original file line number Diff line number Diff line change
Expand Up @@ -58,11 +58,17 @@ function createCountElementEnhancer({

const showText = !(target.dataset.coralNotext === "true");

// replace the placeholder COMMENT_COUNT with current count
const updatedCountHtml = countHtml.replace(
"COMMENT_COUNT",
currentCount.toString()
);

// Update the innerHTML which contains the count and new value..
if (showText) {
element.innerHTML = `${countHtml} ${textHtml}`;
element.innerHTML = `${updatedCountHtml} ${textHtml}`;
} else {
element.innerHTML = countHtml;
element.innerHTML = updatedCountHtml;
}

if (storyID) {
Expand Down
9 changes: 6 additions & 3 deletions src/core/client/embed/index.html
Original file line number Diff line number Diff line change
Expand Up @@ -14,12 +14,15 @@
</head>

<body>
<p style="text-align: center;">
<p style="text-align: center">
<a href="/admin">Admin</a> | <a href="/story.html">Story</a> |
<a href="/storyButton.html">Story With Button</a> |
<a href="http://127.0.0.1:8080/storyAMP.html"> AMP</a>
</p>
<h1 style="text-align: center">Coral – Embed Stream</h1>
<div style="text-align: center">
<span class="coral-count" data-coral-url="http://localhost:8080/"></span>
</div>
<div id="coralStreamEmbed" style="max-width: 640px; margin: 0 auto"></div>
<script>
const CoralStreamEmbed = Coral.createStreamEmbed({
Expand All @@ -30,8 +33,8 @@ <h1 style="text-align: center">Coral – Embed Stream</h1>
* The argument passed is the event emitter from
* https://github.com/asyncly/EventEmitter2
*/
events: function(events) {
events.onAny(function(eventName, data) {
events: function (events) {
events.onAny(function (eventName, data) {
console.debug(eventName, data);
});
},
Expand Down
2 changes: 1 addition & 1 deletion src/core/server/app/handlers/api/story/count.ts
Original file line number Diff line number Diff line change
Expand Up @@ -98,7 +98,7 @@ export const countJSONPHandler =

const count = story ? await calculateStoryCount(mongo, story) : 0;

const countHtml = `<span class="${NUMBER_CLASS_NAME}">${count}</span>`;
const countHtml = `<span class="${NUMBER_CLASS_NAME}">COMMENT_COUNT</span>`;
const textHtml = getTextHTML(tenant, story?.settings.mode, i18n, count);

const data: CountJSONPData = {
Expand Down
2 changes: 1 addition & 1 deletion src/core/server/app/middleware/cache.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ interface CacheEntry {
createdAt: number;
}

async function get(
export async function get(
redis: Redis,
ttl: number,
key: string
Expand Down
2 changes: 1 addition & 1 deletion src/core/server/app/router/api/story.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ export function createStoryRouter(app: AppOptions) {
const cacheDuration = app.config.get("jsonp_cache_max_age");
const immutable = app.config.get("jsonp_cache_immutable");

const router = createAPIRouter({ cacheDuration, immutable });
const router = createAPIRouter({ cacheDuration: "0", immutable });

if (app.config.get("jsonp_response_cache")) {
router.use(cacheMiddleware(app.redis, cacheDuration));
Expand Down
2 changes: 2 additions & 0 deletions src/core/server/graph/mutators/Actions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ export const Actions = (ctx: GraphContext) => ({
ctx.mongo,
ctx.redis,
ctx.cache,
ctx.config,
ctx.broker,
ctx.tenant,
input.commentID,
Expand All @@ -36,6 +37,7 @@ export const Actions = (ctx: GraphContext) => ({
ctx.mongo,
ctx.redis,
ctx.cache,
ctx.config,
ctx.broker,
ctx.tenant,
input.commentID,
Expand Down
1 change: 1 addition & 0 deletions src/core/server/graph/mutators/Comments.ts
Original file line number Diff line number Diff line change
Expand Up @@ -223,6 +223,7 @@ export const Comments = (ctx: GraphContext) => ({
ctx.mongo,
ctx.redis,
ctx.cache,
ctx.config,
ctx.broker,
ctx.tenant,
commentID,
Expand Down
3 changes: 3 additions & 0 deletions src/core/server/services/comments/moderation/moderate.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import { Config } from "coral-server/config";
import { MongoContext } from "coral-server/data/context";
import {
CommentNotFoundError,
Expand All @@ -23,6 +24,7 @@ export type Moderate = Omit<CreateCommentModerationActionInput, "storyID">;
export default async function moderate(
mongo: MongoContext,
redis: AugmentedRedis,
config: Config,
tenant: Tenant,
input: Moderate,
now: Date,
Expand Down Expand Up @@ -110,6 +112,7 @@ export default async function moderate(
const counts = await updateAllCommentCounts(
mongo,
redis,
config,
{
...result,
tenant,
Expand Down
3 changes: 3 additions & 0 deletions src/core/server/stacks/approveComment.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import { Config } from "coral-server/config";
import { DataCache } from "coral-server/data/cache/dataCache";
import { MongoContext } from "coral-server/data/context";
import { CoralEventPublisherBroker } from "coral-server/events/publisher";
Expand All @@ -16,6 +17,7 @@ const approveComment = async (
mongo: MongoContext,
redis: AugmentedRedis,
cache: DataCache,
config: Config,
broker: CoralEventPublisherBroker,
tenant: Tenant,
commentID: string,
Expand All @@ -30,6 +32,7 @@ const approveComment = async (
const { result, counts } = await moderate(
mongo,
redis,
config,
tenant,
{
commentID,
Expand Down
5 changes: 4 additions & 1 deletion src/core/server/stacks/createComment.ts
Original file line number Diff line number Diff line change
Expand Up @@ -94,6 +94,7 @@ const markCommentAsAnswered = async (
mongo: MongoContext,
redis: AugmentedRedis,
cache: DataCache,
config: Config,
broker: CoralEventPublisherBroker,
tenant: Tenant,
comment: Readonly<Comment>,
Expand Down Expand Up @@ -142,6 +143,7 @@ const markCommentAsAnswered = async (
mongo,
redis,
cache,
config,
broker,
tenant,
comment.parentID,
Expand Down Expand Up @@ -383,6 +385,7 @@ export default async function create(
mongo,
redis,
cache,
config,
broker,
tenant,
comment,
Expand Down Expand Up @@ -440,7 +443,7 @@ export default async function create(
}

// Update all the comment counts on stories and users.
const counts = await updateAllCommentCounts(mongo, redis, {
const counts = await updateAllCommentCounts(mongo, redis, config, {
tenant,
actionCounts,
after: comment,
Expand Down
37 changes: 36 additions & 1 deletion src/core/server/stacks/helpers/updateAllCommentCounts.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,9 @@
import { get } from "coral-server/app/middleware/cache";
import { Config } from "coral-server/config";
import { MongoContext } from "coral-server/data/context";
import { EncodedCommentActionCounts } from "coral-server/models/action/comment";
import {
calculateTotalPublishedCommentCount,
Comment,
CommentModerationQueueCounts,
CommentStatusCounts,
Expand Down Expand Up @@ -135,6 +138,7 @@ interface UpdateAllCommentCountsOptions {
export default async function updateAllCommentCounts(
mongo: MongoContext,
redis: AugmentedRedis,
config: Config,
input: UpdateAllCommentCountsInput,
options: UpdateAllCommentCountsOptions = {
updateStory: true,
Expand All @@ -161,12 +165,43 @@ export default async function updateAllCommentCounts(

if (options.updateStory) {
// Update the story, site, and user comment counts.
await updateStoryCounts(mongo, tenant.id, storyID, {
const updatedStory = await updateStoryCounts(mongo, tenant.id, storyID, {
action,
status,
moderationQueue,
tags,
});

// only update Redis cache for comment counts if jsonp_response_cache set to true
if (config.get("jsonp_response_cache")) {
if (updatedStory) {
const totalCount = calculateTotalPublishedCommentCount(
updatedStory.commentCounts.status
);

const key = `rmc:CoralCount&url=${updatedStory.url}`;
const ttl = config.get("jsonp_cache_max_age");
const entry = await get(redis, ttl, key);
if (entry) {
const { body } = entry;

// update count in jsonp data with new total comment count
const bodyArr = body.split(",");
for (let i = 0; i < bodyArr.length; i++) {
if (bodyArr[i].startsWith('"count":')) {
bodyArr[i] = `"count":${totalCount}`;
}
}
const updatedEntry = {
...entry,
body: bodyArr.join(","),
};

// set updated entry with new total comment count in Redis cache
void redis.set(key, JSON.stringify(updatedEntry));
}
}
}
}

if (options.updateSite) {
Expand Down
3 changes: 3 additions & 0 deletions src/core/server/stacks/rejectComment.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import { Config } from "coral-server/config";
import { DataCache } from "coral-server/data/cache/dataCache";
import { MongoContext } from "coral-server/data/context";
import { CoralEventPublisherBroker } from "coral-server/events/publisher";
Expand Down Expand Up @@ -66,6 +67,7 @@ const rejectComment = async (
mongo: MongoContext,
redis: AugmentedRedis,
cache: DataCache,
config: Config,
broker: CoralEventPublisherBroker | null,
tenant: Tenant,
commentID: string,
Expand All @@ -82,6 +84,7 @@ const rejectComment = async (
const { result, counts } = await moderate(
mongo,
redis,
config,
tenant,
{
commentID,
Expand Down

0 comments on commit 99fcf9d

Please sign in to comment.