working TS implementation of twitter app

This commit is contained in:
erik-sn committed 2020-10-13 22:13:47 -04:00
1 parent 2920267ef3
commit f0be5b3f8c
12 files changed
+372 -350

No files matched your search

+4 -2
View File
@@ -3,6 +3,8 @@ import { ESXServer } from "fivem-esx-js/server/esx_server";
import './db';
import './sv_twitter';
let ESX: ESXServer = null;
export let ESX: ESXServer = null;
emit('esx:getSharedObject', (obj: ESXServer) => ESX = obj);
emit('esx:getSharedObject', (obj: ESXServer) => ESX = obj);
export const getSource = () => parseInt(source);
-249
View File
@@ -1,249 +0,0 @@
ESX = nil
TriggerEvent('esx:getSharedObject', function(obj)
ESX = obj
end)
function fetchAllTweets(profileId, cb)
MySQL.Async.fetchAll([[
SELECT
npwd_twitter_profiles.profile_name,
npwd_twitter_profiles.avatar_url,
npwd_twitter_tweets.*,
npwd_twitter_likes.id IS NOT NULL AS isLiked,
TIME_TO_SEC(TIMEDIFF( NOW(), npwd_twitter_tweets.createdAt)) AS seconds_since_tweet
FROM npwd_twitter_tweets
LEFT OUTER JOIN npwd_twitter_profiles ON npwd_twitter_tweets.identifier = npwd_twitter_profiles.identifier
LEFT OUTER JOIN npwd_twitter_likes ON npwd_twitter_tweets.id = npwd_twitter_likes.tweet_id AND npwd_twitter_likes.profile_id = @profileId
WHERE visible = 1
ORDER BY npwd_twitter_tweets.createdAt DESC
LIMIT 100
]],
{ profileId = profileId },
function(tweets)
cb(tweets)
end)
end
function fetchTweetsFiltered(profileId, searchValue, cb)
local searchValueParameterized = '%' .. searchValue .. '%'
MySQL.Async.fetchAll([[
SELECT
npwd_twitter_profiles.profile_name,
npwd_twitter_profiles.avatar_url,
npwd_twitter_tweets.*,
npwd_twitter_likes.id IS NOT NULL AS isLiked,
TIME_TO_SEC(TIMEDIFF( NOW(), npwd_twitter_tweets.createdAt)) AS seconds_since_tweet
FROM npwd_twitter_tweets
LEFT OUTER JOIN npwd_twitter_profiles ON npwd_twitter_tweets.identifier = npwd_twitter_profiles.identifier
LEFT OUTER JOIN npwd_twitter_likes ON npwd_twitter_tweets.id = npwd_twitter_likes.tweet_id AND npwd_twitter_likes.profile_id = @profileId
WHERE visible = 1 AND (npwd_twitter_profiles.profile_name LIKE @profile_name OR npwd_twitter_tweets.message LIKE @message)
ORDER BY npwd_twitter_tweets.createdAt DESC
LIMIT 100
]],
{
profileId = profileId,
profile_name = searchValueParameterized,
message = searchValueParameterized
},
function(tweets)
cb(tweets)
end)
end
-- ESX.RegisterServerCallback('phone:fetchTweets', function(source, cb)
-- local _source = source
-- local xPlayer = ESX.GetPlayerFromId(_source)
-- local _identifier = xPlayer.getIdentifier()
-- getProfile(_identifier, function(result)
-- local profile = result[1]
-- fetchAllTweets(profile.id, cb)
-- end)
-- end)
-- search value expected to be lower case
ESX.RegisterServerCallback('phone:fetchTweetsFiltered', function(source, cb, searchValue)
local _source = source
local xPlayer = ESX.GetPlayerFromId(_source)
local _identifier = xPlayer.getIdentifier()
getProfile(_identifier, function(result)
local profile = result[1]
fetchTweetsFiltered(profile.id, searchValue, cb)
end)
end)
ESX.RegisterServerCallback('phone:createTweet', function(source, cb, data)
local _source = source
local xPlayer = ESX.GetPlayerFromId(_source)
local _identifier = xPlayer.getIdentifier()
MySQL.Async.transaction({[[
INSERT INTO npwd_twitter_tweets (`identifier`, `message`, `images`)
VALUES (@identifier, @message, @images)
]]},
{
identifier = _identifier,
message = data.message,
images = data.images
},
function(result)
cb(result)
end)
end)
function getProfile(identifier, cb)
MySQL.Async.fetchAll([[
SELECT * FROM npwd_twitter_profiles
WHERE identifier = @identifier
LIMIT 1
]],
{ identifier = identifier },
function(result)
cb(result)
end)
end
function getProfileName(identifier, cb)
local defaultProfileName = ''
if Config.twitter.generateProfileNameFromUsers == false then
cb(defaultProfileName)
return
end
-- TODO: make this query configurable
MySQL.Async.fetchAll([[
SELECT CONCAT(firstname, '_', lastname) AS profile_name
FROM users
WHERE identifier = @identifier LIMIT 1
]],
{ identifier = identifier },
function(users)
if next(users) == nil then -- no user found with this identifier
cb(defaultProfileName)
return
end
cb(users[1].profile_name)
end)
end
function createDefaultProfile(identifier, cb)
getProfileName(identifier, function(profileName)
MySQL.Async.execute([[
INSERT INTO npwd_twitter_profiles (`identifier`, `profile_name`)
VALUES (@identifier, @profile_name)
]],
{ identifier = identifier, profile_name = profileName },
function(result)
if result == 1 then -- if we created the profile then return it
getProfile(identifier, cb)
else -- otherwise just give back the failed result
cb(result)
end
end)
end)
end
-- Retrieve a twitter profile by identifier. If it does not exist then
-- create and return it
function getOrCreateProfile(identifier, cb)
getProfile(identifier, function(retrieveResult)
if next(retrieveResult) == nil then -- profile does not exist, attempt to create it
createDefaultProfile(identifier, function(createResult)
cb(createResult)
end)
else -- profile does exist
cb(retrieveResult)
end
end)
end
ESX.RegisterServerCallback('phone:getOrCreateTwitterProfile', function(source, cb)
local _source = source
local xPlayer = ESX.GetPlayerFromId(_source)
local _identifier = xPlayer.getIdentifier()
getOrCreateProfile(_identifier, function(result)
cb(result)
end)
end)
function updateTwitterProfile(identifier, data, cb)
MySQL.Async.transaction({[[
UPDATE npwd_twitter_profiles
SET avatar_url = @avatar_url, profile_name = @profile_name, bio = @bio, location = @location, job = @job
WHERE identifier = @identifier
]]},
{
identifier = identifier,
avatar_url= data.avatar_url,
profile_name = data.profile_name,
bio = data.bio,
location = data.location,
job = data.job,
},
function(result)
cb(result)
end)
end
ESX.RegisterServerCallback('phone:updateTwitterProfile', function(source, cb, data)
local _source = source
local xPlayer = ESX.GetPlayerFromId(_source)
local _identifier = xPlayer.getIdentifier()
updateTwitterProfile(_identifier, data, function(result)
cb(result)
end)
end)
function doesLikeExist(profileId, tweetId, cb)
MySQL.Async.fetchAll([[
SELECT * FROM npwd_twitter_likes
WHERE profile_id = @profileId AND tweet_id = @tweetId
LIMIT 1
]],
{ profileId = profileId, tweetId = tweetId },
function(result)
cb(result)
end)
end
function createLike(profileId, tweetId)
MySQL.Async.execute([[
INSERT INTO npwd_twitter_likes (`profile_id`, `tweet_id`)
VALUES (@profileId, @tweetId)
]],
{ profileId = profileId, tweetId = tweetId })
end
function deleteLike(profileId, tweetId)
MySQL.Async.execute([[
DELETE FROM npwd_twitter_likes
WHERE profile_id = @profileId AND tweet_id = @tweetId
]],
{ profileId = profileId, tweetId = tweetId })
end
RegisterServerEvent('phone:toggleLike')
AddEventHandler('phone:toggleLike', function(tweetId)
local _source = source
local xPlayer = ESX.GetPlayerFromId(_source)
local _identifier = xPlayer.getIdentifier()
getProfile(_identifier, function(result)
local profile = result[1]
doesLikeExist(profile.id, tweetId, function(result)
if next(result) == nil then -- like doesn't exist
createLike(profile.id, tweetId)
else -- like does exist
deleteLike(profile.id, tweetId)
end
end)
end)
end)
+236 -11
View File
@@ -1,7 +1,40 @@
import { pool } from './db';
import { ESX, getSource } from './server';
import events from '../utils/events';
import config from '../utils/config';
async function fetchAllTweets(profileId: number) {
interface Profile {
id: number;
profile_name: string;
identifier: string;
avatar_url?: string;
bio?: string;
location?: string;
job?: string;
createdAt: string;
updatedAt: string;
}
interface ProfileName {
profile_name: string;
}
interface Tweet {
id: number;
profile_name?: string;
avatar_url?: string;
message: string;
createdAt?: string;
updatedAt?: string;
images?: string;
likes?: number;
}
/**
* Retrieve the latest 100 tweets
* @param profileId - twitter profile id of the player
*/
async function fetchAllTweets(profileId: number): Promise<Tweet[]> {
const query = `
SELECT
npwd_twitter_profiles.profile_name,
@@ -17,10 +50,17 @@ async function fetchAllTweets(profileId: number) {
LIMIT 100
`;
const [ results ] = await pool.query(query, [profileId]);
return results;
const tweets = <Tweet[]>results;
return tweets;
}
async function fetchTweetsFiltered(profileId: number, searchValue: string) {
/**
* Fetch tweets by some search value submitted by the user. Intended to let
* player's search for tweets by profile, message or more.
* @param profileId - twitter profile id of the player
* @param searchValue - value to search
*/
async function fetchTweetsFiltered(profileId: number, searchValue: string): Promise<Tweet[]> {
const parameterizedSearchValue = `%${searchValue}%`;
const query = `
SELECT
@@ -32,28 +72,213 @@ async function fetchTweetsFiltered(profileId: number, searchValue: string) {
FROM npwd_twitter_tweets
LEFT OUTER JOIN npwd_twitter_profiles ON npwd_twitter_tweets.identifier = npwd_twitter_profiles.identifier
LEFT OUTER JOIN npwd_twitter_likes ON npwd_twitter_tweets.id = npwd_twitter_likes.tweet_id AND npwd_twitter_likes.profile_id = ?
WHERE visible = 1 AND (npwd_twitter_profiles.profile_name LIKE @profile_name OR npwd_twitter_tweets.message LIKE ?)
WHERE visible = 1 AND (npwd_twitter_profiles.profile_name LIKE ? OR npwd_twitter_tweets.message LIKE ?)
ORDER BY npwd_twitter_tweets.createdAt DESC
LIMIT 100
`;
const [ results ] = await pool.query(query, [profileId, parameterizedSearchValue]);
return results;
const [ results ] = await pool.query(query, [profileId, parameterizedSearchValue, parameterizedSearchValue]);
const tweets = <Tweet[]>results;
return tweets;
}
async function getProfile(identifier: string) {
/**
* Creates a tweet in the database
* @param identifier - player identifier
* @param tweet - tweet to be created
*/
async function createTweet(identifier: string, tweet: Tweet): Promise<any> {
const query = `
INSERT INTO npwd_twitter_tweets (identifier, message, images)
VALUES (?, ?, ?)
`
await pool.query(query, [identifier, tweet.message, tweet.images])
}
/**
* Retrieve a player's twitter profile by their identifier
* @param identifier - player identifier
*/
async function getProfile(identifier: string): Promise<Profile | null> {
const query = `
SELECT * FROM npwd_twitter_profiles
WHERE identifier = ?
LIMIT 1
`;
const [results] = await pool.query(query, [identifier]);
const [ results ] = await pool.query(query, [identifier]);
const profiles = <Profile[]>results;
return profiles.length > 0 ? profiles[0] : null;
}
/**
* Generate a twitter profile name by the player's name
* @param identifier - player's identifier
*/
async function generateProfileName(identifier: string): Promise<string> {
const defaultProfileName = '';
if (!config.twitter.generateProfileNameFromUsers) return defaultProfileName;
const query = `
SELECT CONCAT(firstname, '_', lastname) AS profile_name
FROM users
WHERE identifier = ? LIMIT 1
`
const [ results ] = await pool.query(query, [identifier]);
const profileNames = <ProfileName[]>results;
if (profileNames.length === 0) return defaultProfileName;
return profileNames[0].profile_name;
}
/**
* Create a default twitter profile for a player. This is the intial profile
* that all player's will receive and can then customize.
* @param identifier - player's identifier
*/
async function createDefaultProfile(identifier: string): Promise<Profile> {
const profileName = await generateProfileName(identifier);
const query = `
INSERT INTO npwd_twitter_profiles (identifier, profile_name)
VALUES (?, ?)
`
const [ result ] = await pool.execute(query, [identifier, profileName]);
return getProfile(identifier);
}
/**
* Retrieve the player's profile by their identifier if it exists. If
* not, create it and return it.
* @param identifier - player's identifier
*/
async function getOrCreateProfile(identifier: string): Promise<Profile> {
const profile = await getProfile(identifier);
return profile || await createDefaultProfile(identifier);
}
async function updateProfile(identifier: string, profile: Profile) {
const { avatar_url, profile_name, bio, location, job } = profile;
const query = `
UPDATE npwd_twitter_profiles
SET avatar_url = ?, profile_name = ?, bio = ?, location = ?, job = ?
WHERE identifier = ?
`
await pool.execute(query, [
avatar_url,
profile_name,
bio,
location,
job,
identifier
]);
}
/**
* Create a "like" in the database that ties a profile & tweet together
* @param profileId - primary key of the profile conducting the like
* @param tweetId - primary key of the tweet being liked
*/
async function createLike(profileId: number, tweetId: number): Promise<void> {
const query = `
INSERT INTO npwd_twitter_likes (profile_id, tweet_id)
VALUES (?, ?)
`
await pool.execute(query, [profileId, tweetId]);
}
/**
* Delete a "like" relationship from the database
* @param profileId - primary key of the profile removing the like
* @param tweetId - primary key of the tweet to remove the like from
*/
async function deleteLike(profileId: number, tweetId: number): Promise<void> {
const query = `
DELETE FROM npwd_twitter_likes
WHERE profile_id = ? AND tweet_id = ?
`
await pool.execute(query, [profileId, tweetId]);
}
/**
* Check if a "like" relationship between a profile and a tweet exists
* @param profileId - primary key of the profile to check
* @param tweetId - primary key of the tweet to check
*/
async function doesLikeExist(profileId: number, tweetId: number): Promise<boolean> {
const query = `
SELECT * FROM npwd_twitter_likes
WHERE profile_id = ? AND tweet_id = ?
LIMIT 1
`
const [ results ] = await pool.query(query, [profileId, tweetId]);
const likes = <any[]>results;
return likes.length > 0;
}
onNet(events.TWITTER_GET_OR_CREATE_PROFILE, async () => {
try {
const identifier = ESX.GetPlayerFromId(getSource()).getIdentifier();
const profile = await getOrCreateProfile(identifier)
emitNet(events.TWITTER_GET_OR_CREATE_PROFILE_SUCCESS, getSource(), profile);
} catch (e) {
emitNet(events.TWITTER_GET_OR_CREATE_PROFILE_FAILURE, getSource());
}
});
onNet(events.TWITTER_UPDATE_PROFILE, async (profile: Profile) => {
try {
const identifier = ESX.GetPlayerFromId(getSource()).getIdentifier();
await updateProfile(identifier, profile)
emitNet(events.TWITTER_UPDATE_PROFILE_RESULT, getSource(), true);
} catch (e) {
emitNet(events.TWITTER_UPDATE_PROFILE_RESULT, getSource(), false);
}
});
onNet(events.TWITTER_FETCH_TWEETS, async () => {
try {
const results = await fetchAllTweets(24);
emitNet(events.TWITTER_FETCH_TWEETS_SUCCESS, source, results);
const identifier = ESX.GetPlayerFromId(getSource()).getIdentifier();
const profile = await getProfile(identifier);
const tweets = await fetchAllTweets(profile.id);
emitNet(events.TWITTER_FETCH_TWEETS_SUCCESS, getSource(), tweets);
} catch (e) {
emitNet(events.TWITTER_FETCH_TWEETS_FAILURE, source);
emitNet(events.TWITTER_FETCH_TWEETS_FAILURE, getSource());
}
});
onNet(events.TWITTER_FETCH_TWEETS_FILTERED, async (searchValue: string) => {
try {
const identifier = ESX.GetPlayerFromId(getSource()).getIdentifier();
const profile = await getProfile(identifier);
const tweets = await fetchTweetsFiltered(profile.id, searchValue);
emitNet(events.TWITTER_FETCH_TWEETS_FILTERED_SUCCESS, getSource(), tweets);
} catch (e) {
emitNet(events.TWITTER_FETCH_TWEETS_FILTERED_FAILURE, getSource());
}
});
onNet(events.TWITTER_CREATE_TWEET, async (tweet: Tweet) => {
try {
const identifier = ESX.GetPlayerFromId(getSource()).getIdentifier();
await createTweet(identifier, tweet);
emitNet(events.TWITTER_CREATE_TWEET_RESULT, getSource(), true);
} catch (e) {
emitNet(events.TWITTER_CREATE_TWEET_RESULT, getSource(), false);
}
});
onNet(events.TWITTER_TOGGLE_LIKE, async (tweetId: number) => {
try {
const identifier = ESX.GetPlayerFromId(getSource()).getIdentifier();
const profile = await getOrCreateProfile(identifier)
const likeExists = await doesLikeExist(profile.id, tweetId);
if (likeExists) {
await deleteLike(profile.id, tweetId);
} else {
await createLike(profile.id, tweetId);
}
emitNet(events.TWITTER_TOGGLE_LIKE_SUCCESS, getSource());
} catch (e) {
emitNet(events.TWITTER_TOGGLE_LIKE_FAILURE, getSource());
}
});