Skip to content

Commit

Permalink
Merge pull request #840 from Regalijan/split-getplayerinfo
Browse files Browse the repository at this point in the history
Split getPlayerInfo into smaller methods
  • Loading branch information
Regalijan authored Dec 12, 2024
2 parents efb89d8 + ab0ac76 commit f4b8801
Show file tree
Hide file tree
Showing 11 changed files with 309 additions and 30 deletions.
36 changes: 36 additions & 0 deletions lib/friends/getFollowerCount.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
// Includes
const http = require('../util/http.js').func

// Args
exports.required = ['userId']

// Docs
/**
* ✅ Gets the number of followers a user has.
* @category User
* @alias getFollowerCount
* @param { number } userId
* @returns Promise<number>
* @example const noblox = require("noblox.js")
* const numberOfFollowers = await noblox.getFollowerCount(55549140)
**/

// Define
exports.func = function (userId) {
const httpOpt = {
url: `//friends.roblox.com/v1/users/${userId}/followers/count`,
options: {
json: true,
method: 'GET',
resolveWithFullResponse: true
}
}

return http(httpOpt).then(function (res) {
if (res.statusCode === 200) { return res.body.count }

throw new Error(
`Failed to retrieve follower count: (${res.statusCode}) ${res.body}`
)
})
}
36 changes: 36 additions & 0 deletions lib/friends/getFollowingCount.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
// Includes
const http = require('../util/http.js').func

// Args
exports.required = ['userId']

// Docs
/**
* ✅ Gets the number of users a user is following.
* @category User
* @alias getFollowingCount
* @param { number } userId
* @returns Promise<number>
* @example const noblox = require("noblox.js")
* const numberOfFollowings = await noblox.getFollowingCount(55549140)
**/

// Define
exports.func = function (userId) {
const httpOpt = {
url: `//friends.roblox.com/v1/users/${userId}/followings/count`,
options: {
json: true,
method: 'GET',
resolveWithFullResponse: true
}
}

return http(httpOpt).then(function (res) {
if (res.statusCode === 200) { return res.body.count }

throw new Error(
`Failed to retrieve following count: (${res.statusCode}) ${res.body}`
)
})
}
36 changes: 36 additions & 0 deletions lib/friends/getFriendCount.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
// Includes
const http = require('../util/http.js').func

// Args
exports.required = ['userId']

// Docs
/**
* ✅ Gets the number of friends a user has.
* @category User
* @alias getFriendCount
* @param { number } userId
* @returns Promise<number>
* @example const noblox = require("noblox.js")
* const numberOfFriends = await noblox.getFriendCount(55549140)
**/

// Define
exports.func = function (userId) {
const httpOpt = {
url: `//friends.roblox.com/v1/users/${userId}/friends/count`,
options: {
json: true,
method: 'GET',
resolveWithFullResponse: true
}
}

return http(httpOpt).then(function (res) {
if (res.statusCode === 200) { return res.body.count }

throw new Error(
`Failed to retrieve friend count: (${res.statusCode}) ${res.body}`
)
})
}
5 changes: 5 additions & 0 deletions lib/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -77,8 +77,11 @@ noblox.onGroupTransaction = require('./economy/onGroupTransaction.js')
noblox.acceptFriendRequest = require('./friends/acceptFriendRequest.js')
noblox.declineAllFriendRequests = require('./friends/declineAllFriendRequests.js')
noblox.declineFriendRequest = require('./friends/declineFriendRequest.js')
noblox.getFollowerCount = require('./friends/getFollowerCount.js')
noblox.getFollowers = require('./friends/getFollowers.js')
noblox.getFollowingCount = require('./friends/getFollowingCount.js')
noblox.getFollowings = require('./friends/getFollowings.js')
noblox.getFriendCount = require('./friends/getFriendCount.js')
noblox.getFriendRequests = require('./friends/getFriendRequests.js')
noblox.getFriends = require('./friends/getFriends.js')
noblox.onFriendRequest = require('./friends/onFriendRequest.js')
Expand Down Expand Up @@ -167,7 +170,9 @@ noblox.sendTrade = require('./trades/sendTrade.js')
noblox.getBlurb = require('./users/getBlurb.js')
noblox.getIdFromUsername = require('./users/getIdFromUsername.js')
noblox.getPlayerInfo = require('./users/getPlayerInfo.js')
noblox.getUserInfo = require('./users/getUserInfo.js')
noblox.getUsernameFromId = require('./users/getUsernameFromId.js')
noblox.getUsernameHistory = require('./users/getUsernameHistory.js')
noblox.onBlurbChange = require('./users/onBlurbChange.js')
noblox.searchUsers = require('./users/searchUsers.js')
noblox.clearSession = require('./util/clearSession.js')
Expand Down
36 changes: 14 additions & 22 deletions lib/users/getPlayerInfo.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,9 @@
// Includes
const http = require('../util/http.js').func
const getPageResults = require('../util/getPageResults.js').func
const getFollowingCount = require('../friends/getFollowingCount.js').func
const getFollowerCount = require('../friends/getFollowerCount.js').func
const getFriendCount = require('../friends/getFriendCount.js').func
const getUserInfo = require('../users/getUserInfo.js').func
const getUsernameHistory = require('../users/getUsernameHistory.js').func

// Args
exports.required = ['userId']
Expand All @@ -20,11 +23,11 @@ exports.required = ['userId']
function getPlayerInfo (userId) {
return new Promise((resolve, reject) => {
const requests = [
constructRequest(`//users.roblox.com/v1/users/${userId}`),
constructRequest(`//friends.roblox.com/v1/users/${userId}/friends/count`),
constructRequest(`//friends.roblox.com/v1/users/${userId}/followings/count`),
constructRequest(`//friends.roblox.com/v1/users/${userId}/followers/count`),
getPageResults({ url: `//users.roblox.com/v1/users/${userId}/username-history`, query: {}, limit: 1000 })
getUserInfo(userId),
getFriendCount(userId),
getFollowingCount(userId),
getFollowerCount(userId),
getUsernameHistory({ userId })
].map(promise => promise.then(
val => ({ status: 'fulfilled', value: val }),
rej => ({ status: 'rejected', reason: rej })
Expand Down Expand Up @@ -53,11 +56,11 @@ function getPlayerInfo (userId) {
} else if (failedResponse) {
reject(new Error('User does not exist.'))
} else {
const responseBodies = responses.map(res => res.body)
const responseBodies = responses.map(res => res.body ?? res)
const oldNames = responses[4].map(nameObject => nameObject.name) || []
const friendCount = responseBodies[1].count
const followerCount = responseBodies[3].count
const followingCount = responseBodies[2].count
const friendCount = responseBodies[1]
const followerCount = responseBodies[3]
const followingCount = responseBodies[2]
const joinDate = new Date(userBody.created)
const blurb = userBody.description
const isBanned = userBody.isBanned
Expand All @@ -84,17 +87,6 @@ function getPlayerInfo (userId) {
})
}

function constructRequest (url) {
return http({
url,
options: {
resolveWithFullResponse: true,
followRedirect: false,
json: true
}
})
}

exports.func = (args) => {
return getPlayerInfo(args.userId)
}
34 changes: 34 additions & 0 deletions lib/users/getUserInfo.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
// Includes
const http = require('../util/http.js').func

// Args
exports.required = ['userId']

// Docs
/**
* ✅ Get base-level user profile information
* @category User
* @alias getUserInfo
* @param { number } userId
* @returns {Promise<UserInfo>}
**/

// Define
exports.func = function (userId) {
const httpOpt = {
url: `//users.roblox.com/v1/users/${userId}`,
options: {
json: true,
method: 'GET',
resolveWithFullResponse: true
}
}

return http(httpOpt).then(function (res) {
if (res.statusCode !== 200) { throw new Error(`Failed to fetch user information: ${res.body.errors?.join(', ')}`) }

res.body.created = new Date(res.body.created)

return res.body
})
}
35 changes: 35 additions & 0 deletions lib/users/getUsernameHistory.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
// Includes
const getPageResults = require('../util/getPageResults.js').func

// Args
exports.required = ['userId']
exports.optional = ['limit', 'sortOrder', 'pageCursor']

// Docs
/**
* ✅ Get a user's username history.
* @category User
* @alias getUsernameHistory
* @param {number} userId
* @param {Limit=} [limit=10]
* @param {SortOrder=} [sortOrder=Asc]
* @param {string} cursor
* @returns {Promise<UsernameHistoryEntry[]>}
* @example const noblox = require("noblox.js")
* const history = await noblox.getUsernameHistory({ userId: 1, limit: 10, sortOrder: "Asc", cursor: "somecursorstring" })
**/

// Define
function getUsernameHistory (userId, limit, sortOrder, cursor) {
return getPageResults({
url: `//users.roblox.com/v1/users/${userId}/username-history`,
query: {},
limit,
pageCursor: cursor,
sortOrder
})
}

exports.func = function (args) {
return getUsernameHistory(args.userId, args.limit, args.sortOrder, args.cursor)
}
20 changes: 19 additions & 1 deletion test/friends.test.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
const { acceptFriendRequest, declineAllFriendRequests, declineFriendRequest, getFollowers, getFollowings, getFriendRequests, getFriends, removeFriend, sendFriendRequest, unfollow, setCookie } = require('../lib')
const { acceptFriendRequest, declineAllFriendRequests, declineFriendRequest, getFollowerCount, getFollowers, getFollowingCount, getFollowings, getFriendCount, getFriendRequests, getFriends, removeFriend, sendFriendRequest, unfollow, setCookie } = require('../lib')

beforeAll(() => {
return new Promise(resolve => {
Expand Down Expand Up @@ -32,6 +32,12 @@ describe('Friends Methods', () => {
return await expect(unfollow(55549140)).resolves.not.toThrow()
})

it('getFollowerCount() returns the number of user\'s followers', () => {
return getFollowerCount(55549140).then((res) => {
return expect(res).toBeGreaterThanOrEqual(0)
})
})

it('getFollowers() returns a user\'s followers', () => {
return getFollowers(55549140).then((res) => {
return expect(res).toMatchObject({
Expand All @@ -48,6 +54,12 @@ describe('Friends Methods', () => {
})
})

it('getFollowingCount() returns the number of users that are following the user', () => {
return getFollowingCount(55549140).then((res) => {
return expect(res).toBeGreaterThanOrEqual(0)
})
})

it('getFollowings() returns which users are being followed by the specified user', () => {
return getFollowings(55549140).then((res) => {
return expect(res).toMatchObject({
Expand All @@ -64,6 +76,12 @@ describe('Friends Methods', () => {
})
})

it('getFriendCount() returns the number of friends the specified user has', () => {
return getFriendCount(55549140).then((res) => {
return expect(res).toBeGreaterThanOrEqual(0)
})
})

it('getFriendRequests() returns the logged in user\'s incoming friend requests', () => {
return getFriendRequests().then((res) => {
return expect(res).toMatchObject({
Expand Down
39 changes: 33 additions & 6 deletions test/users.test.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
const { getBlurb, getIdFromUsername, getPlayerInfo, getUsernameFromId, searchUsers, setCookie } = require('../lib')
const { getBlurb, getIdFromUsername, getPlayerInfo, getUserInfo, getUsernameFromId, getUsernameHistory, searchUsers, setCookie } = require('../lib')

beforeAll(() => {
return new Promise(resolve => {
Expand Down Expand Up @@ -60,22 +60,49 @@ describe('Users Methods', () => {
})
})

it('getUserInfo() returns profile information on the specified user', () => {
return getUserInfo(55549140).then((res) => {
return expect(res).toMatchObject({
description: expect.any(String),
created: expect.any(Date),
isBanned: expect.any(Boolean),
externalAppDisplayName: expect.any(null),
hasVerifiedBadge: expect.any(Boolean),
id: expect.any(Number),
name: expect.any(String),
displayName: expect.any(String)
})
})
})

it('getUsernameFromId() returns a player\'s username given an ID', () => {
return getUsernameFromId(1).then((res) => {
return expect(res).toEqual(expect.any(String))
})
})

it('getUsernameHistory() returns a player\'s username history', () => {
return getUsernameHistory(55549140).then((res) => {
return expect(res).toMatchObject(
expect.arrayContaining([
expect.objectContaining({
name: expect.any(String)
})
])
)
})
})

it('searchUsers() returns results for the specified keyword', () => {
return searchUsers('roblox').then((res) => {
return expect(res).toMatchObject(
expect.arrayContaining([
expect.objectContaining({
previousUsernames: expect.any(Array),
hasVerifiedBadge: expect.any(Boolean),
id: expect.any(Number),
name: expect.any(String),
displayName: expect.any(String)
previousUsernames: expect.any(Array),
hasVerifiedBadge: expect.any(Boolean),
id: expect.any(Number),
name: expect.any(String),
displayName: expect.any(String)
})
])
)
Expand Down
Loading

0 comments on commit f4b8801

Please sign in to comment.