Skip to content
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

Added preview-as anonymous/free/paid to previews endpoint #22168

Open
wants to merge 1 commit into
base: main
Choose a base branch
from

Conversation

kevinansfield
Copy link
Member

@kevinansfield kevinansfield commented Feb 11, 2025

ref https://linear.app/ghost/issue/PLG-352

  • updated /p/ endpoint to accept an optional ?memberStatus query parameter with three allowed values: anonymous/free/paid
    • using a query parameter allows for post previews to be opened in a new tab and still display segmented views
  • when a memberStatus query param is provided:
    • frame.apiType is set to content which triggers the content-gating paths of our output serializer's post mapper
    • where needed, frame.original.context.member is set to a minimal member object with a status property to allow content-gating NQL queries to match
    • the combination of both switches our preview API output to match what the Content API does when rendering posts with a particular logged-in member status
  • if no memberStatus query param is provided the existing behaviour is preserved, where we render as we do for Admin API requests, showing content for all segments simultaneously

ref https://linear.app/ghost/issue/PLG-352

- updated `/p/` endpoint to accept an optional `?memberStatus` query parameter with three allowed values: `anonymous/free/paid`
- when a `memberStatus` query param is provided:
  - `frame.apiType` is set to `content` which triggers the content-gating paths of our output serializer's post mapper
  - where needed, `frame.original.content.member` is set to a minimal member object with a `status` property to allow content-gating NQL queries to match
  - the combination of both changes our API output to match what the Content API does when rendering posts with a particular logged-in member status
- if no `memberStatus` query param is provided the existing behaviour is preserved of rendering as we do for Admin API requests, showing content for all segments simultaneously
Copy link
Contributor

coderabbitai bot commented Feb 11, 2025

Walkthrough

This pull request introduces modifications across both the frontend and backend preview handling. On the frontend, an additional property, memberStatus, is now included in the params object of the previewController, capturing the value from the query string. On the server side, a constant ALLOWED_MEMBER_STATUSES has been added, and a helper function _addMemberContextToFrame has been implemented to adjust the response context based on the provided member status. Additionally, validations in the API have been updated to restrict memberStatus to the allowed values, and the options array is expanded accordingly. The changes are further validated with new and updated unit and end-to-end tests that specifically check the behavior under different member statuses. Finally, a utility method for inserting gated posts has been added to the test fixtures.

Possibly related PRs

Suggested labels

browser-tests

✨ Finishing Touches
  • 📝 Generate Docstrings (Beta)

Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR. (Beta)
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 0

🧹 Nitpick comments (4)
ghost/core/core/server/api/endpoints/previews.js (2)

13-36: Consider enhancing error handling in _addMemberContextToFrame.

The helper function could be more defensive:

  1. Validate frame.options early
  2. Use object literals instead of multiple if statements

Consider this refactoring:

 const _addMemberContextToFrame = (frame) => {
-    if (!frame?.options?.memberStatus) {
+    if (!frame?.options) {
         return;
     }
+    const {memberStatus} = frame.options;
+    if (!memberStatus) {
+        return;
+    }
 
     frame.apiType = 'content';
     frame.original ??= {};
     frame.original.context ??= {};
 
-    if (frame.options?.memberStatus === 'free') {
-        frame.original.context.member = {
-            status: 'free'
-        };
-    }
-
-    if (frame.options?.memberStatus === 'paid') {
-        frame.original.context.member = {
-            status: 'paid'
-        };
-    }
+    const memberContextMap = {
+        free: {status: 'free'},
+        paid: {status: 'paid'}
+    };
+    
+    frame.original.context.member = memberContextMap[memberStatus];
 };

69-71: Consider adding error logging.

The function call to _addMemberContextToFrame should include error logging to help with debugging.

 query(frame) {
+    try {
         _addMemberContextToFrame(frame);
+    } catch (err) {
+        debug('Failed to add member context to frame:', err);
+    }
ghost/core/test/unit/frontend/services/routing/controllers/previews.test.js (1)

69-74: Consider adding test cases for memberStatus variations.

The test only covers undefined memberStatus. Consider adding test cases for:

  • Anonymous member
  • Free member
  • Paid member
ghost/core/core/frontend/services/routing/controllers/previews.js (1)

22-24: Consider validating memberStatus input.

The memberStatus is directly passed from query params without validation. Consider validating against ALLOWED_MEMBER_STATUSES.

+const {ALLOWED_MEMBER_STATUSES} = require('../../../../server/api/endpoints/previews');
 const params = {
     uuid: req.params.uuid,
     status: 'all',
     include: 'authors,tags,tiers',
-    memberStatus: req.query?.memberStatus
+    memberStatus: ALLOWED_MEMBER_STATUSES.includes(req.query?.memberStatus) ? req.query.memberStatus : undefined
 };
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between a1e1a2f and 67249e4.

📒 Files selected for processing (6)
  • ghost/core/core/frontend/services/routing/controllers/previews.js (1 hunks)
  • ghost/core/core/server/api/endpoints/previews.js (4 hunks)
  • ghost/core/test/e2e-frontend/preview_routes.test.js (2 hunks)
  • ghost/core/test/unit/api/endpoints/previews.test.js (1 hunks)
  • ghost/core/test/unit/frontend/services/routing/controllers/previews.test.js (1 hunks)
  • ghost/core/test/utils/fixture-utils.js (1 hunks)
🔇 Additional comments (4)
ghost/core/test/unit/api/endpoints/previews.test.js (1)

1-56: Well-structured and comprehensive test coverage!

The test suite effectively covers all scenarios for the new memberStatus feature, including:

  • Status-based API type setting
  • Member context population
  • Edge cases (anonymous, undefined)
ghost/core/test/e2e-frontend/preview_routes.test.js (2)

69-78: LGTM!

The test case effectively verifies content gating for free members by checking both the presence of content before the paywall and the absence of content after the paywall.


80-89: LGTM!

The test case effectively verifies content gating for paid members by checking the presence of content both before and after the paywall.

ghost/core/test/utils/fixture-utils.js (1)

149-167: LGTM!

The function effectively sets up test data for gated posts by:

  1. Creating a post with appropriate properties (id, title, status, etc.)
  2. Including a paywall marker in the content
  3. Setting the visibility to 'paid'

This provides good test coverage for the preview-as functionality.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant