69 lines
2.9 KiB
TypeScript
69 lines
2.9 KiB
TypeScript
import { RedditUser } from '../model/User';
|
|
import RedditSessionManager from '../session/SessionManager';
|
|
|
|
/**
|
|
* Provides services for interacting with Reddit user data and sending messages.
|
|
*/
|
|
export class RedditService {
|
|
|
|
/**
|
|
* Retrieves information about a Reddit user.
|
|
*
|
|
* @param {string} username - The username of the Reddit user to retrieve information for.
|
|
* @returns {Promise<RedditUser>} A promise that resolves with the RedditUser object containing user information.
|
|
* @throws {Error} Throws an error if fetching user information fails.
|
|
* @example
|
|
* RedditService.getUserInfo('exampleUser')
|
|
* .then(userInfo => console.log(userInfo))
|
|
* .catch(error => console.error(error));
|
|
*/
|
|
static async getUserInfo(username: string): Promise<RedditUser> {
|
|
try {
|
|
const redditSession = await RedditSessionManager.getInstance()
|
|
const response = await redditSession.axiosInstance.get(`/user/${username}/about`);
|
|
return response.data;
|
|
} catch (error) {
|
|
console.error('Error fetching user info:', error);
|
|
throw error;
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Sends a private message to a Reddit user.
|
|
*
|
|
* @param {string} username - The username of the recipient Reddit user.
|
|
* @param {string} subject - The subject of the message.
|
|
* @param {string} message - The body text of the message.
|
|
* @returns {Promise<void>} A promise that resolves when the message is successfully sent.
|
|
* @throws {Error} Throws an error if sending the message fails.
|
|
* @example
|
|
* RedditService.sendMessage('exampleUser', 'Hello', 'This is a test message.')
|
|
* .then(() => console.log('Message sent successfully.'))
|
|
* .catch(error => console.error('Error sending message:', error));
|
|
*/
|
|
static async sendMessage(username: string, subject: string, message: string): Promise<void> {
|
|
try {
|
|
const redditSession = await RedditSessionManager.getInstance();
|
|
// Create a URLSearchParams object with your data
|
|
const params = new URLSearchParams();
|
|
params.append('api_type', 'json');
|
|
params.append('to', `u/${username}`);
|
|
params.append('subject', subject);
|
|
params.append('text', message);
|
|
|
|
// Use the params object directly in the data field
|
|
await redditSession.axiosInstance.post('/api/compose', params, {
|
|
headers: {
|
|
// Ensure the content type is set to application/x-www-form-urlencoded
|
|
'Content-Type': 'application/x-www-form-urlencoded'
|
|
}
|
|
});
|
|
console.log(JSON.stringify(params, null, 4))
|
|
console.log(`Message sent to ${username}`);
|
|
} catch (error) {
|
|
console.error('Error sending message:', error);
|
|
throw error;
|
|
}
|
|
}
|
|
}
|