Skip to content

关注接口

类说明

Follows 类提供用户关注功能,包括添加关注、取消关注、检查关注状态、获取关注列表和粉丝列表等。

功能特点:

  • 支持关注和取消关注操作
  • 不能关注自己
  • 防止重复关注
  • 支持分页查询关注列表和粉丝列表
  • 未登录用户可以查看关注状态

添加关注

Method : POST

URL : /wp-json/vtheme/v1/follows

Auth required : True

Headers :

  • Authorization: Bearer
  • Content-Type: application/json

Body :

json
{
  "following_id": 5
}

参数说明:

  • following_id : [integer] 要关注的用户ID

Success Response

Code : 201 Created

Content example :

json
{
  "success": true,
  "message": "Followed successfully",
  "is_following": true,
  "following_id": 5
}

Error Response

Code : 400 Bad Request

Content examples :

json
{
  "error": "Invalid user ID"
}
json
{
  "error": "You cannot follow yourself"
}
json
{
  "error": "You are already following this user"
}

Code : 401 Unauthorized

Content example :

json
{
  "error": "Please login first"
}

Code : 404 Not Found

Content example :

json
{
  "error": "User not found"
}

Code : 500 Internal Server Error

Content example :

json
{
  "error": "Failed to follow user"
}

取消关注

Method : DELETE

URL : /wp-json/vtheme/v1/follows/{user_id}

Auth required : True

URL Parameters :

  • user_id : [integer] 要取消关注的用户ID

Headers :

  • Authorization: Bearer

Success Response

Code : 200 OK

Content example :

json
{
  "success": true,
  "message": "Unfollowed successfully",
  "is_following": false,
  "following_id": 5
}

Error Response

Code : 400 Bad Request

Content example :

json
{
  "error": "Invalid user ID"
}

Code : 401 Unauthorized

Content example :

json
{
  "error": "Please login first"
}

Code : 500 Internal Server Error

Content example :

json
{
  "error": "Failed to unfollow user"
}

检查关注状态

Method : GET

URL : /wp-json/vtheme/v1/users/{user_id}/follow-status

Auth required : False

URL Parameters :

  • user_id : [integer] 目标用户ID

Success Response

Code : 200 OK

Content example (已登录且已关注) :

json
{
  "is_following": true,
  "target_user_id": 5,
  "current_user_id": 1
}

Content example (未登录或未关注) :

json
{
  "is_following": false,
  "target_user_id": 5,
  "current_user_id": 1
}

注意: 未登录时 current_user_id 字段不存在

Error Response

Code : 400 Bad Request

Content example :

json
{
  "error": "Invalid user ID"
}

获取我的关注列表

Method : GET

URL : /wp-json/vtheme/v1/follows/my-following

Auth required : True

Headers :

  • Authorization: Bearer

Query Parameters :

  • page : [integer] 页码,默认1
  • per_page : [integer] 每页数量,默认20(范围1-100)

Success Response

Code : 200 OK

Content example :

json
{
  "data": [
    {
      "id": 1,
      "follower_id": 1,
      "following_id": 5,
      "created_at": "2023-01-01 12:00:00",
      "display_name": "张三",
      "user_email": "zhangsan@example.com",
      "user_registered": "2022-01-01 00:00:00"
    },
    {
      "id": 2,
      "follower_id": 1,
      "following_id": 8,
      "created_at": "2023-01-02 12:00:00",
      "display_name": "李四",
      "user_email": "lisi@example.com",
      "user_registered": "2022-02-01 00:00:00"
    }
  ],
  "total": 50,
  "page": 1,
  "per_page": 20,
  "total_pages": 3
}

Error Response

Code : 401 Unauthorized

Content example :

json
{
  "error": "Please login first"
}

获取我的粉丝列表

Method : GET

URL : /wp-json/vtheme/v1/follows/my-followers

Auth required : True

Headers :

  • Authorization: Bearer

Query Parameters :

  • page : [integer] 页码,默认1
  • per_page : [integer] 每页数量,默认20(范围1-100)

Success Response

Code : 200 OK

Content example :

json
{
  "data": [
    {
      "id": 1,
      "follower_id": 10,
      "following_id": 1,
      "created_at": "2023-01-01 12:00:00",
      "display_name": "王五",
      "user_email": "wangwu@example.com",
      "user_registered": "2022-03-01 00:00:00"
    }
  ],
  "total": 100,
  "page": 1,
  "per_page": 20,
  "total_pages": 5
}

Error Response

Code : 401 Unauthorized

Content example :

json
{
  "error": "Please login first"
}

使用示例

关注/取消关注

javascript
// 关注用户
function followUser(userId) {
  fetch('/wp-json/vtheme/v1/follows', {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
      'Authorization': 'Bearer ' + token
    },
    body: JSON.stringify({
      following_id: userId
    })
  })
  .then(response => response.json())
  .then(data => {
    if (data.success) {
      console.log('关注成功');
      // 更新UI,显示"已关注"按钮
      updateFollowButton(userId, true);
    }
  })
  .catch(error => {
    console.error('关注失败:', error);
  });
}

// 取消关注
function unfollowUser(userId) {
  fetch(`/wp-json/vtheme/v1/follows/${userId}`, {
    method: 'DELETE',
    headers: {
      'Authorization': 'Bearer ' + token
    }
  })
  .then(response => response.json())
  .then(data => {
    if (data.success) {
      console.log('取消关注成功');
      // 更新UI,显示"关注"按钮
      updateFollowButton(userId, false);
    }
  })
  .catch(error => {
    console.error('取消关注失败:', error);
  });
}

检查关注状态

javascript
// 检查是否已关注某用户
function checkFollowStatus(userId) {
  fetch(`/wp-json/vtheme/v1/users/${userId}/follow-status`)
    .then(response => response.json())
    .then(data => {
      if (data.is_following) {
        // 已关注,显示"已关注"按钮
        updateFollowButton(userId, true);
      } else {
        // 未关注,显示"关注"按钮
        updateFollowButton(userId, false);
      }
    });
}

// 页面加载时检查
checkFollowStatus(5);

获取关注列表

javascript
// 获取我的关注列表
function getMyFollowing(page = 1) {
  fetch(`/wp-json/vtheme/v1/follows/my-following?page=${page}&per_page=20`, {
    headers: {
      'Authorization': 'Bearer ' + token
    }
  })
  .then(response => response.json())
  .then(data => {
    console.log('关注列表:', data.data);
    console.log('总数:', data.total);
    console.log('总页数:', data.total_pages);
    
    // 渲染列表
    renderFollowingList(data.data);
  });
}

// 获取我的粉丝列表
function getMyFollowers(page = 1) {
  fetch(`/wp-json/vtheme/v1/follows/my-followers?page=${page}&per_page=20`, {
    headers: {
      'Authorization': 'Bearer ' + token
    }
  })
  .then(response => response.json())
  .then(data => {
    console.log('粉丝列表:', data.data);
    
    // 渲染列表
    renderFollowersList(data.data);
  });
}

完整的关注按钮组件

javascript
class FollowButton {
  constructor(container, userId) {
    this.container = container;
    this.userId = userId;
    this.init();
  }
  
  init() {
    // 检查登录状态
    if (!ajax_object.current_user_id) {
      this.renderLoginButton();
      return;
    }
    
    // 不能关注自己
    if (ajax_object.current_user_id == this.userId) {
      this.container.style.display = 'none';
      return;
    }
    
    // 检查关注状态
    this.checkStatus();
    
    // 绑定点击事件
    this.container.addEventListener('click', () => this.handleClick());
  }
  
  checkStatus() {
    fetch(`/wp-json/vtheme/v1/users/${this.userId}/follow-status`)
      .then(response => response.json())
      .then(data => {
        this.isFollowing = data.is_following;
        this.render();
      });
  }
  
  handleClick() {
    if (this.isFollowing) {
      this.unfollow();
    } else {
      this.follow();
    }
  }
  
  follow() {
    fetch('/wp-json/vtheme/v1/follows', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'Authorization': 'Bearer ' + ajax_object.wp_rest_nonce
      },
      body: JSON.stringify({
        following_id: this.userId
      })
    })
    .then(response => response.json())
    .then(data => {
      if (data.success) {
        this.isFollowing = true;
        this.render();
      }
    });
  }
  
  unfollow() {
    fetch(`/wp-json/vtheme/v1/follows/${this.userId}`, {
      method: 'DELETE',
      headers: {
        'Authorization': 'Bearer ' + ajax_object.wp_rest_nonce
      }
    })
    .then(response => response.json())
    .then(data => {
      if (data.success) {
        this.isFollowing = false;
        this.render();
      }
    });
  }
  
  render() {
    if (this.isFollowing) {
      this.container.innerHTML = '<button class="btn-followed">已关注</button>';
    } else {
      this.container.innerHTML = '<button class="btn-follow">+ 关注</button>';
    }
  }
  
  renderLoginButton() {
    this.container.innerHTML = '<button class="btn-login">登录后关注</button>';
  }
}

// 使用
new FollowButton(document.getElementById('follow-btn'), 5);

注意事项

  1. 权限控制

    • 关注和取消关注需要登录
    • 查看关注状态不需要登录
    • 获取列表需要登录
  2. 业务规则

    • 不能关注自己
    • 不能重复关注
    • 取消关注是幂等操作
  3. 分页处理

    • 每页数量限制在1-100之间
    • 建议默认20条每页
    • 返回列表包含分页信息
  4. 用户体验

    • 关注操作应该即时反馈
    • 可以添加加载状态
    • 错误时要给用户明确提示
  5. 性能优化

    • 关注状态可以缓存
    • 列表数据可以考虑懒加载
    • 避免频繁请求同一数据