repo_name
stringlengths
5
122
path
stringlengths
3
232
text
stringlengths
6
1.05M
EdRamos12/Proffy
web/src/components/TeacherItem/index.tsx
import React, { useState, useEffect, useCallback, useContext } from 'react'; import './styles.css' import whatsappIcon from '../../assets/images/icons/whatsapp.svg'; import trashIcon from '../../assets/images/icons/trash.svg'; import api from '../../services/api'; import { Link } from 'react-router-dom'; import AuthContext from '../../contexts/AuthContext'; import NotificationContext from '../../contexts/NotificationContext'; import { v4 } from 'uuid'; interface Schedule { week_day: number; from: number; to: number; class_id: number; } interface ScheduleProps { schedule: Schedule[]; week_day: number; style?: Object; id?: string; } export interface Teacher { avatar: string; bio: string; cost: number; id: number; name: string; subject: string; whatsapp: string; user_id: number; schedule: Schedule[]; }; interface teacherItemProps { teacher: Teacher; } const ScheduleItem: React.FC<ScheduleProps> = ({ schedule, week_day, ...rest }) => { const sortedSchedule = schedule.sort(function (a, b) { return a.week_day - b.week_day; }); const [currentMinute, setCurrentMinute] = useState<String[]>([]); const [hasSchedule, setHasSchedule] = useState(false); const [currentDay, setCurrentDay] = useState(''); const week = [ { value: '0', label: 'Sunday' }, { value: '1', label: 'Monday' }, { value: '2', label: 'Tuesday' }, { value: '3', label: 'Wednesday' }, { value: '4', label: 'Thursday' }, { value: '5', label: 'Friday' }, { value: '6', label: 'Saturday' }, ]; function searchSchedule(nameKey: any, Schedule: any) { for (let i = 0; i < Schedule.length; i++) { if (Schedule[i].week_day === nameKey) { return Schedule[i]; } } return false; } function searchWeek(nameKey: any, WeekArray: any) { for (let i = 0; i < WeekArray.length; i++) { if (WeekArray[i].value === nameKey) { return WeekArray[i].label; } } return false; } function convertMinsToHrsMins(mins: number) { let hours = Math.floor(Number(mins) / 60); let minutes = Number(mins) % 60; return `${hours < 10 ? '0' + hours : hours}h${minutes < 10 ? '0' + minutes : minutes}`; } const displayScheduleOnScreen = useCallback(() => { const result = searchSchedule(week_day, sortedSchedule); const scheduleFromHrs = convertMinsToHrsMins(result.from); const scheduleToHrs = convertMinsToHrsMins(result.to); setHasSchedule(Boolean(result)); setCurrentMinute([scheduleFromHrs, scheduleToHrs]); setCurrentDay(searchWeek(String(week_day), week)); }, [sortedSchedule, week, week_day]); useEffect(displayScheduleOnScreen, []); return ( <div className="item" id={hasSchedule ? '' : 'schedule-disabled'} {...rest} > <div> <p>Day</p> <h2>{currentDay}</h2> </div> <div> <p>Time</p> <h2>{hasSchedule ? `${currentMinute[0]} - ${currentMinute[1]}` : '-'}</h2> </div> </div> ); } const TeacherItem: React.FC<teacherItemProps> = ({ teacher }) => { const { user } = useContext(AuthContext); const dispatch = useContext(NotificationContext); function createConnection() { api.post('/connections', { user_id: teacher.user_id }, {withCredentials: true}); } async function handleDelete() { const result = window.confirm('Are you sure you want to delete your class?'); if (result) { await api.delete('/classes/'+teacher.id, {withCredentials: true}); dispatch({ type: "ADD_NOTIFICATION", payload: { type: 'SUCCESS', message: 'Selected class has been deleted. Refreshing the page in a few instants.', title: 'Class deleted!', id: v4(), } }); setTimeout(() => { window.location.reload(); }, 4000) } } return ( <article className="teacher-item"> <header> <Link to={`/profile/${teacher.user_id}`}> <img src={teacher.avatar} alt="" /> </Link> <div> <Link to={`/profile/${teacher.user_id}`}><strong>{teacher.name}</strong></Link> <span>{teacher.subject}</span> </div> { user?.id === teacher.user_id && <button id='can-edit' onClick={handleDelete}> <img src={trashIcon} alt="Delete" /> </button> } </header> <p>{teacher.bio}</p> <div id="schedules"> <div className="top-container"> <ScheduleItem schedule={teacher.schedule} week_day={0} /> <ScheduleItem schedule={teacher.schedule} week_day={1} /> <ScheduleItem schedule={teacher.schedule} week_day={2} /> <ScheduleItem schedule={teacher.schedule} week_day={3} /> </div> <div className="bottom-container"> <ScheduleItem schedule={teacher.schedule} week_day={4} /> <ScheduleItem schedule={teacher.schedule} week_day={5} /> <ScheduleItem schedule={teacher.schedule} week_day={6} /> </div> </div> <footer> <div> <p>Price/Hour <strong>$ {teacher.cost}</strong></p> </div> <a rel="noopener noreferrer" target="_blank" onClick={createConnection} href={`https://wa.me/${teacher.whatsapp}`}> <img src={whatsappIcon} alt="" /> Enter in contact </a> </footer> </article> ); } export default TeacherItem;
EdRamos12/Proffy
web/src/pages/LoadingPublic/index.tsx
<reponame>EdRamos12/Proffy import logoImg from '../../assets/images/logo.svg'; import loadingGif from '../../assets/images/loading.gif'; import './styles.css'; export default function LoadingScreen() { return ( <div className="loading-container"> <div className="loading-background"> <img height="20%" src={logoImg} alt="Proffy" /> <img height="10%" src={loadingGif} alt="Loading"/> </div> </div> ); }
EdRamos12/Proffy
server/src/controllers/ClassCommentsController.ts
<gh_stars>1-10 import { Request, Response } from 'express'; import db from '../db/connections'; export default class ClassCommentsController { async create(rq: Request, rsp: Response) { const { content } = rq.body; const { class_id } = rq.params; const trx = await db.transaction(); try { const user_id = rq.userId; const insertedClassComment = await trx('class_comment').insert({ content, class_id, user_id }); console.log(insertedClassComment); await trx.commit(); return rsp.status(201).send(); } catch (err) { return rsp.status(500).send(); } } async index(rq: Request, rsp: Response) { const { class_id } = rq.params; const post = await db('classes').where('id', '=', class_id); if (post.length == 0) return rsp.status(400).send({ message: 'Invalid Id' }); const comments_post = await db('class_comment').where('class_id', '=', class_id); if (comments_post.length == 0) return rsp.status(404).send({ message: 'No comments found' }); return rsp.json(comments_post); } async delete(rq: Request, rsp: Response) { const { class_id, id } = rq.params; const post = await db('classes').where('id', '=', class_id); if (post.length == 0) return rsp.status(400).send({ message: 'Invalid Id' }); const comments_post = await db('class_comment').where('id', '=', id); if (comments_post.length == 0) return rsp.status(404).send({ message: 'No comments found' }); const user_id = rq.userId; console.log(user_id); //console.log(post, comments_post) if (user_id !== post[0].user_id || user_id !== comments_post[0].user_id) return rsp.status(400).send({ message: 'Unauthorized' }); const trx = await db.transaction(); await trx('class_comment').where('id', '=', id).delete(); await trx.commit(); return rsp.send({ message: 'Comment deleted.' }) } }
EdRamos12/Proffy
web/src/services/api.ts
<reponame>EdRamos12/Proffy<filename>web/src/services/api.ts<gh_stars>1-10 import axios from 'axios'; const api = axios.create({ baseURL: 'http://localhost:3333/api/v2' }) export default api;
EdRamos12/Proffy
web/src/components/PageHeader/index.tsx
<reponame>EdRamos12/Proffy<filename>web/src/components/PageHeader/index.tsx import React from 'react'; import { useHistory } from 'react-router-dom'; import './styles.css' import logoIcon from '../../assets/images/logo.svg' import backIcon from '../../assets/images/icons/back.svg' interface PageHeaderProps { title?: string; description?: string; page?: string; background?: string; icon?: string; info?: string; } const PageHeader: React.FC<PageHeaderProps> = (props) => { const history = useHistory(); return ( <header className="page-header" style={{backgroundImage: `url(${props.background})`}}> <div className="top-bar-container"> <div className="top-bar-content"> <div> <img onClick={history.goBack} src={backIcon} alt="go back" /> </div> {props.page} <img onClick={() => history.push('/home')} src={logoIcon} alt="ye" /> </div> </div> <div className="header-content"> { Boolean(props.title) && <div className="header-container"> <div className="title-container"> <strong>{props.title}</strong> { props.description && <p>{ props.description }</p> } </div> { Boolean(props.info) && <div className="info-container"> { props.icon && <img src={props.icon} alt=""/> } <p> { props.info } </p> </div> } </div> } {props.children} </div> </header> ); } export default PageHeader;
EdRamos12/Proffy
server/src/controllers/ProfileController.ts
import { Request, Response } from 'express'; import knex from '../db/connections'; export default class ProfileController { async edit(rq: Request, rsp: Response) { const { whatsapp, bio, name } = rq.body; const trx = await knex.transaction(); try { let profile; if (rq.file !== undefined) { profile = await trx('profile').where('user_id', '=', rq.userId).update({ whatsapp, bio, avatar: 'http://localhost:3333/uploads/'+rq.file.filename, }); } else { profile = await trx('profile').where('user_id', '=', rq.userId).update({ whatsapp, bio, }); } await trx('users').where('id', '=', rq.userId).update({ name }); await trx.commit(); return rsp.send({ profile }); } catch (err) { await trx.commit(); return rsp.status(400).send({ message: err }); } } }
EdRamos12/Proffy
server/src/controllers/ConnectionsController.ts
import { Request, Response } from 'express'; import db from '../db/connections'; export default class ConnectionsController { async index(rq: Request, rsp: Response) { const totalConnections = await db('connections').count('* as total'); const { total } = totalConnections[0]; return rsp.json({ total }) } async create(rq: Request, rsp: Response) { const {user_id} = rq.body; if (rq.userId == user_id) { console.log('bruh'); return rsp.status(401).send({ message: 'You cannot create connections on your own class!' }); } await db('connections').insert({ user_id }); return rsp.status(201).send(); } }
EdRamos12/Proffy
web/src/pages/TeacherForm/index.tsx
import React, { useState, FormEvent, useContext, useEffect } from 'react'; import Input from '../../components/Input'; import PageHeader from '../../components/PageHeader'; import warningIcon from '../../assets/images/icons/warning.svg' import './styles.css'; import Textarea from '../../components/Textarea'; import Select from '../../components/Select'; import api from '../../services/api'; import AuthContext from '../../contexts/AuthContext'; import SuccessContainer from '../../components/SuccessContainer'; import RocketIcon from '../../assets/images/icons/rocket.svg'; import { Link } from 'react-router-dom'; import NotificationContext from '../../contexts/NotificationContext'; import { v4 } from 'uuid'; import Cleave from 'cleave.js/react'; function TeacherForm() { const { user } = useContext(AuthContext); const [bio, setBio] = useState(''); const [whatsapp, setWhatsapp] = useState(''); const [subject, setSubject] = useState(''); const [cost, setCost] = useState(''); const [success, setSuccess] = useState(false); const [scheduleItems, setScheduleItems] = useState([{ week_day: 0, from: '', to: '' }]); const dispatch = useContext(NotificationContext); function addNewScheduleItem() { setScheduleItems([ ...scheduleItems, { week_day: 0, from: '', to: '' } ]) } function setScheduleItemValue(position: number, field: string, value: string) { const newArray = scheduleItems.map((scheduleItem, index) => { if (index === position) { return {...scheduleItem, [field]: value} } return scheduleItem; }); setScheduleItems(newArray); } function deleteScheduleItem(index: number) { if (scheduleItems.length > 1) { const newSchedule = scheduleItems.slice(0, index).concat(scheduleItems.slice(index + 1, scheduleItems.length)); setScheduleItems(newSchedule); } else { dispatch({ type: "ADD_NOTIFICATION", payload: { type: 'ERROR', message: 'You should have at least one schedule to your class!', title: 'Something went wrong.', id: v4(), } }); } } function handleOnSubmitClass(e: FormEvent) { e.preventDefault(); api.post('/classes', { subject, cost: cost, schedule: scheduleItems }, {withCredentials: true}).then(() => { setSuccess(true); }).catch((err) => { dispatch({ type: "ADD_NOTIFICATION", payload: { type: 'ERROR', message: 'Check console dev for more details. Contact us if possible: '+err, title: 'Something went wrong.', id: v4(), } }); //alert('Something went wrong! Check log for more details \n '+err); console.error(err); }); } useEffect(() => { setWhatsapp(String(user?.whatsapp)); setBio(String(user?.bio)); }, [user]) return ( <div id="page-teacher-form" className="container"> <SuccessContainer success={success} title="Registration saved!" button_text="Return home"> All right, your registration is on our list of teachers. <br /> Now just keep an eye on your WhatsApp. πŸ˜‰ </SuccessContainer> <PageHeader page="Give classes" info='Get ready! it will be amazing.' icon={RocketIcon} title="How amazing that you want to teach." description="The first step is to fill this subscription form."/> <main> <form onSubmit={handleOnSubmitClass}> <fieldset> <legend>Personal data</legend> <div className="profile-and-whatsapp"> <div className="profile"> <Link to={`/profile/${user?.id}`}> <img src={user?.avatar} alt="Avatar"/> </Link> <Link style={{textDecoration: 'none'}} to={`/profile/${user?.id}`}> <h2>{user?.name}</h2> </Link> </div> <Input value={whatsapp === 'null' ? 'Go to your profile and change me!' : whatsapp} required readOnly label="Whatsapp" name="whatsapp" /> </div> <Textarea required readOnly value={bio === 'null' ? 'Go to your profile and change me!' : bio} name="bio" label="Biography" onChange={(e) => {setBio(e.target.value)}} /> </fieldset> <fieldset> <legend>About the class</legend> <div id="two-inputs-row"> <Select required name="subject" label="School subject" value={subject} onChange={(e) => {setSubject(e.target.value)}} options={[ { value: 'Arts', label: 'Arts' }, { value: 'Biology', label: 'Biology' }, { value: 'Chemistry', label: 'Chemistry' }, { value: 'Physical education', label: 'Physical education' }, { value: 'Physics', label: 'Physics' }, { value: 'Geography', label: 'Geography' }, { value: 'History', label: 'History' }, { value: 'Math', label: 'Math' }, { value: 'English', label: 'English' }, { value: 'Philosophy', label: 'Philosophy' }, { value: 'Sociology', label: 'Sociology' }, ]} /> {/* <Cleave name="" label="" }}> </Cleave> */} <div className="input-block" id="Class's cost per hour"> <label htmlFor="cost">Class's cost per hour</label> <Cleave id="cost" value={cost} required style={{paddingLeft: '3.4rem'}} onChange={(e) => {setCost(e.target.value)}} options={{ numeral: true, numeralThousandsGroupStyle: 'thousand' }} /> <span id="currency-span">$</span> </div> </div> </fieldset> <fieldset> <legend>Available time <button type="button" onClick={addNewScheduleItem}>+ New time</button></legend> {scheduleItems.map((scheduleItem, index) => { return ( <div key={index} className="schedule-item"> <Select required value={scheduleItem.week_day} custom_id="Subject" name="week_day" onChange={(e) => {setScheduleItemValue(index, 'week_day', e.target.value)}} label="Day of the week" options={[ { value: '0', label: 'Sunday' }, { value: '1', label: 'Monday' }, { value: '2', label: 'Tuesday' }, { value: '3', label: 'Wednesday' }, { value: '4', label: 'Thursday' }, { value: '5', label: 'Friday' }, { value: '6', label: 'Saturday' }, ]} /> <Input required value={scheduleItem.from} onChange={(e) => {setScheduleItemValue(index, 'from', e.target.value)}} name="from" label="From" type="time"/> <Input required value={scheduleItem.to} onChange={(e) => {setScheduleItemValue(index, 'to', e.target.value)}} name="to" label="To" type="time"/> {scheduleItems.length > 1 && <div className="delete-container"> <button id="delete-item" type="button" onClick={(e) => deleteScheduleItem(index)}>Delete schedule</button> </div>} </div> ); })} </fieldset> <footer> <p><img src={warningIcon} alt="Important warning"/> Important <br /> Fill up all fields correctly.</p> <button type="submit"> Submit </button> </footer> </form> </main> </div> ); } export default TeacherForm;
EdRamos12/Proffy
web/src/pages/Reset/index.tsx
<reponame>EdRamos12/Proffy<filename>web/src/pages/Reset/index.tsx import React, { useState, FormEvent, useEffect, useContext } from 'react' import { Link, useParams } from 'react-router-dom'; import logoImg from '../../assets/images/logo.svg'; import backIcon from '../../assets/images/icons/back.svg' import SuccessContainer from '../../components/SuccessContainer'; import api from '../../services/api'; export default function Reset() { const { token } = useParams() as any; const [success, setSuccess] = useState(false); const [error, setError] = useState(''); const [password, setPassword] = useState(''); async function handleForgotPass(e: FormEvent) { e.preventDefault(); try { await api.post('/reset_password', { token, password }); setSuccess(true); } catch (error) { console.log({ error }) setError(error.response.data.message); } } useEffect(() => { setError(''); }, [password]) return ( <div id="register-page"> <SuccessContainer title="Password reset!" success={success} button_text="Sign in!"> Your password has been successfully redefined! <br /> You can now log in to the app. </SuccessContainer> <div id="register-page-content"> <Link to='/' id="go-back"> <img src={backIcon} alt="go back" /> </Link> <form onSubmit={handleForgotPass} id="register-form"> <fieldset> <div id="register-form-header"> <h1>Reset password</h1> <p id="description"> Insert a new password to log in. </p> <span><strong>{error}</strong></span> </div> <div className="input-block" id="Password"> <label htmlFor="Password-input" id={Boolean(password) ? "active" : ""}>New password</label> <input required style={{ borderRadius: '10px' }} className={Boolean(error) ? "input-error" : ""} type="password" id="Password-input" onChange={(e) => { setPassword(e.target.value) }} /> </div> <button type="submit" disabled={!Boolean(password)}> Send </button> </fieldset> </form> <div id="register-bg-container"> <div id="register-bg-items-container"> <div> <img src={logoImg} alt="Proffy" /> <h2>Your online platform <br /> to study.</h2> </div> </div> </div> </div> </div> ); }
EdRamos12/Proffy
web/src/pages/TeacherList/index.tsx
<reponame>EdRamos12/Proffy import React, { useState, FormEvent, useEffect, useMemo, useContext } from 'react'; import './styles.css' import PageHeader from '../../components/PageHeader'; import TeacherItem, { Teacher } from '../../components/TeacherItem'; import Input from '../../components/Input'; import Select from '../../components/Select'; import SmileIcon from '../../assets/images/icons/smile.svg'; import api from '../../services/api'; import PostStorage from '../../contexts/PostStorage'; function paramsToObject(params: any) { const urlParams = new URLSearchParams(params); return Object.fromEntries(urlParams); } const TeacherList = () => { // load chunked posts const { storedPage, chunkInfo, storedPosts } = useContext(PostStorage); //actual posts const [teachers, setTeachers] = useState([]); // general values const [page, setPage] = useState(1); const [total, setTotal] = useState(0); const [totalClasses, setTotalClasses] = useState('.....'); const [loading, setLoading] = useState(false); const [search, setSearch] = useState(false); // search thing const [subject, setSubject] = useState(''); const [week_day, setWeekDay] = useState(''); const [time, setTime] = useState(''); // no more posts to load const [limitReached, setLimitReached] = useState(false); // scroll value const [bottomPageValue, setBottomPageValue] = useState(0); async function makeSearch(e: FormEvent) { e.preventDefault(); window.history.pushState({}, "", `/study?subject=${subject}&week_day=${week_day}&time=${time}`); setTotal(0); setPage(1); setTeachers([] as any); setLimitReached(false); setSearch(true); setLoading(true); } const checkChunkedPosts = useMemo(() => async function a() { if (storedPosts !== null && storedPosts !== teachers) { //console.log(storedPosts, teachers) setPage(storedPage + 1); setTeachers(storedPosts as never[]); //console.log('is it?', teachers); } else { if (window.location.search) { //console.log('about that') const params = paramsToObject(window.location.search); if (!!params.subject && !!params.week_day && !!params.time) { setSubject(params.subject.replace('%20', ' ')); setWeekDay(params.week_day); setTime(params.time); setSearch(true); } } //initial page load setLoading(true); } }, [storedPosts, storedPage, teachers]); // TODO: Maker another algorithm to cancel search // useEffect(() => { // const params = paramsToObject(window.location.search); // if (!window.location.pathname.includes("study")) return; // if (!params.subject && !params.week_day && !params.time) { // //window.history.pushState({}, "", ""); // console.log("wow") // setTeachers([]); // setPage(1); // setSearch(false); // chunkInfo(1, []); // setLoading(true); // } // }, [window.location.search]); useEffect(() => { api.get('/total_classes', { withCredentials: true }).then((info) => { setTotalClasses(info.data.total); }); checkChunkedPosts(); function handleScroll() { if (window.innerHeight + document.documentElement.scrollTop < document.documentElement.scrollHeight - 700) return; if (bottomPageValue === document.documentElement.scrollHeight) return; setBottomPageValue(document.documentElement.scrollHeight); setLoading(true); } window.addEventListener('scroll', handleScroll); return () => window.removeEventListener('scroll', handleScroll); }, [bottomPageValue]); const loadClasses = useMemo(() => async function a() { if (total > 0 && teachers.length === total) { setLoading(false); setLimitReached(true); return; } if (limitReached) { setLoading(false); return; } let response; if (search) { response = await api.get('/classes', { params: { page, subject, week_day, time }, withCredentials: true }); if (page === 1) { setTeachers(response.data as any); } else { setTeachers([...teachers, ...response.data] as any); } } else { response = await api.get('/classes', { params: { page, }, withCredentials: true }); setTeachers([...teachers, ...response.data] as any); } if (response.data.length === 0) { setLoading(false); setLimitReached(true); return; } setPage(page + 1); setLoading(false); setTotal(response.headers['x-total-count']); chunkInfo(page, [...teachers, ...response.data]); return; }, [limitReached, search, subject, time, week_day, page, teachers, total, chunkInfo]); useEffect(() => { if (!loading) return; loadClasses(); }, [loading]); return ( <div id="page-teacher-list" className="container"> <PageHeader icon={SmileIcon} info={`We have ${totalClasses} total classes.`} title="These are the available teachers." page="Study"> <form id="search-teachers" onSubmit={makeSearch}> <Select value={subject} onChange={(e) => { setSubject(e.target.value) }} required name="subject" label="School subject" options={[ { value: 'Art', label: 'Art' }, { value: 'Biology', label: 'Biology' }, { value: 'Chemistry', label: 'Chemistry' }, { value: 'Physical education', label: 'Physical education' }, { value: 'Physics', label: 'Physics' }, { value: 'Geography', label: 'Geography' }, { value: 'History', label: 'History' }, { value: 'Math', label: 'Math' }, { value: 'English', label: 'English' }, { value: 'Philosophy', label: 'Philosophy' }, { value: 'Sociology', label: 'Sociology' }, ]} /> <Select value={week_day} onChange={(e) => { setWeekDay(e.target.value) }} required name="week_day" label="Day of the week" options={[ { value: '0', label: 'Sunday' }, { value: '1', label: 'Monday' }, { value: '2', label: 'Tuesday' }, { value: '3', label: 'Wednesday' }, { value: '4', label: 'Thursday' }, { value: '5', label: 'Friday' }, { value: '6', label: 'Saturday' }, ]} /> <Input value={time} onChange={(e) => { setTime(e.target.value) }} required type="time" name="time" label="Time of the day" /> <button type="submit">Search</button> </form> </PageHeader> <main > {teachers.map((teacher: Teacher, index) => { return <TeacherItem key={index} teacher={teacher} />; })} <span id="limit-message"> {limitReached && 'These are all the results'} {loading && 'Loading...'} <br /> {total === 0 && limitReached ? 'No teacher Found.' : ''} </span> </main> </div> ); } export default TeacherList;
EdRamos12/Proffy
web/src/pages/Confirm/index.tsx
<reponame>EdRamos12/Proffy<gh_stars>1-10 import React, { useContext, useEffect } from 'react'; import { useParams, useHistory } from 'react-router-dom'; import api from '../../services/api'; import { v4 } from 'uuid'; import NotificationContext from '../../contexts/NotificationContext'; import LoadingScreen from '../LoadingPublic'; export default function Confirm() { const { token } = useParams() as any; const history = useHistory(); const dispatch = useContext(NotificationContext); useEffect(() => { (async () => { try { await api.get('/confirmation/'+token); dispatch({ type: "ADD_NOTIFICATION", payload: { type: 'SUCCESS', message: 'You can now log in to the platform.', title: 'E-mail confirmed!', id: v4(), } }); } catch (error) { dispatch({ type: "ADD_NOTIFICATION", payload: { type: 'ERROR', message: "Token validation for confirming e-mail went wrong. Please generate a new one by re-creating your account.", title: 'Something went wrong.', id: v4(), } }); } history.push('/'); })(); }, [token, history]) return LoadingScreen(); }
EdRamos12/Proffy
web/src/pages/ClassPage/index.tsx
<reponame>EdRamos12/Proffy import logoIcon from '../../assets/images/logo.svg'; import backIcon from '../../assets/images/icons/back.svg'; import { useHistory, useParams } from 'react-router-dom'; import './styles.css'; import React, { useEffect, useState } from 'react'; import api from '../../services/api'; import TeacherItem, { Teacher } from '../../components/TeacherItem'; export default function ClassPage() { const history = useHistory(); const [post, setPost] = useState<Teacher[]>([]) as any; const { id } = useParams() as any; useEffect(() => { let isMounted = true; api.get(`/classes/${id}`, { withCredentials: true }).then(teacher => { if (isMounted) { setPost(teacher.data); } }) return () => { isMounted = false; } }, [id, post]); return ( <div id="post-page"> <div className="top-bar-container"> <div className="top-bar-content"> <div> <img onClick={history.goBack} src={backIcon} alt="go back" /> </div> Post <img onClick={() => history.push('/home')} src={logoIcon} alt="ye" /> </div> </div> {post.map((teacher: Teacher, index: number) => { return <TeacherItem key={index} teacher={teacher} />; })} </div> ) }
EdRamos12/Proffy
web/src/pages/Login/index.tsx
<reponame>EdRamos12/Proffy import React, { useState, useContext, FormEvent, useEffect } from 'react'; import AuthContext from '../../contexts/AuthContext'; import { useHistory, Link } from 'react-router-dom'; import logoImg from '../../assets/images/logo.svg'; import heartIcon from '../../assets/images/icons/purple-heart.svg'; import './styles.css'; export default function Login() { const history = useHistory(); const [email, setEmail] = useState(''); const [password, setPassword] = useState(''); const [rememberMe, setRememberMe] = useState(false); const { signIn } = useContext(AuthContext); const [error, setError] = useState(''); //const [showPassword, setShowPassword] = useState(false); async function handleSignIn(e: FormEvent) { e.preventDefault(); const response = await signIn(email, password, rememberMe); if (response) history.push('/home'); else setError('Invalid login'); } function handleDisabledButton() { if (email.length !== 0 && password.length !== 0) { return false; } return true; } useEffect(() => { setError(''); }, [email, password]) return ( <div id="login-page"> <div id="login-page-content"> <div id="login-bg-container"> <div id="login-bg-items-container"> <div> <img src={logoImg} alt="Proffy"/> <h2>Your online platform <br /> to study.</h2> </div> </div> </div> <form onSubmit={handleSignIn} id="login-form"> <fieldset> <h1>Sign In</h1> <span><strong>{error}</strong></span> <div className="input-block" id="Email"> <label htmlFor="Email-input" id={Boolean(email) ? "active" : ""}>Email</label> <input type="email" className={Boolean(error) ? "input-error" : ""} id="Email-input" onChange={(e) => { setEmail(e.target.value) }} /> </div> <div className="input-block" id="Password"> <label htmlFor="Password-input" id={Boolean(password) ? "active" : ""}>Password</label> <input type="password" className={Boolean(error) ? "input-error" : ""} id="Password-input" onChange={(e) => { setPassword(e.target.value) }} /> </div> <div id="login-bottom"> <div> <input id="remember_me" name='remember_me' type='checkbox' onChange={(e) => { setRememberMe(e.target.checked) }} /> <span id="remember-me" /> <label htmlFor="remember_me"> Remember me</label> </div> <Link id="forgot-password" to="/forgot-password">Forgot my password</Link> </div> <button type="submit" disabled={handleDisabledButton()} onClick={handleSignIn}> Enter </button> </fieldset> <footer> <p> Not registered yet? <br /> <Link to="/register">Register</Link> </p> <p id="footer-right-content"> It's free <img src={heartIcon} alt="Heart" /> </p> </footer> </form> </div> </div> ); }
EdRamos12/Proffy
server/src/controllers/UserController.ts
<gh_stars>1-10 import { Request, Response, NextFunction } from 'express'; import db from '../db/connections'; import bcrypt from 'bcrypt'; import jwt from 'jsonwebtoken'; import { createTransport } from 'nodemailer'; import nodeMailerConfig from '../config/nodemailer.json'; require('dotenv/config'); async function sendMail(to: string, subject: string, content: string, text: string) { const transporter = createTransport({ ...nodeMailerConfig, auth: { user: process.env.MAIL_USER, pass: process.env.MAIL_PASS } }); const emailHTML = ` <div style="margin:0px auto; max-width:640px; background:#8257E5"> <a href="http://localhost:3000" target="_blank" style="text-align: center"> <img width="640" src="https://i.imgur.com/tVuGWLt.png" style="z-index: 0;" /> </a> <div style="text-align:center; vertical-align:top; padding:40px 70px; background:#8257E5; display: flex;"> <div style="background: white; padding: 32px; z-index: 1; border-radius: 8px; font-family: Poppins; font-style: normal; font-weight: normal; font-size: 16px; line-height: 26px; color: #6A6180; font-family: tahoma, serif; font-size: 20px;"> ${content} </div> </div> </div> `; const mailOptions = { from: `"Proffy πŸ’œ" <${process.env.MAIL_USER}>`, to, subject, text, html: emailHTML }; const info = await transporter.sendMail(mailOptions); return info.messageId; } export default class UserController { async create(rq: Request, rsp: Response) { try { let { name, email, password } = rq.body; let avatar; if (rq.file === undefined) { avatar = 'https://external-content.duckduckgo.com/iu/?u=https%3A%2F%2Fi.stack.imgur.com%2F34AD2.jpg?' } else { avatar = 'http://localhost:3333/uploads/' + rq.file.filename; } const registered = await db('users').where('email', '=', email); if (registered.length != 0 && registered[0].confirmed) { return rsp.status(400).send({ message: 'Email already in use' }); } const trx = await db.transaction(); const salt = await bcrypt.genSalt(10); const hashedPassword = await bcrypt.hash(password, salt); if (registered.length != 0 && !registered[0].confirmed) { await trx('users').where('id', '=', registered[0].id).update({ name, email, password: <PASSWORD> }); await trx('profile').where('user_id', '=', registered[0].id).update({ avatar }); await trx.commit(); const token = jwt.sign({ id: registered[0].id }, String(process.env.JWT_REGISTER), { expiresIn: 86400, }) const link = `http://localhost:3000/confirm/${token}`; const content = ` <p>Thank you for registering an account for Proffy πŸ’œ! Before entering your account, we need to confirm if it's really you! Click below to verify your e-mail</p> <p>This link is valid for 24 hours, once it expires, you can register again to receive this e-mail again.</p> <a href=${link} target="_blank" style="margin-top: 20px; display: block; text-decoration: none; border: none; background: #916BEA; padding: 3%; border-radius: 0.8rem; color: white; padding: 15px 30px;">Verify!</a> ` sendMail(email, 'E-mail verification from Proffy', content, `Thank you for registering an account for Proffy πŸ’œ! Before entering your account, we need to confirm if it's really you! Click below to verify your e-mail ${link}`); return rsp.status(202).send({ id: registered[0].id }); } const user = await trx('users').insert({ name, email, password: <PASSWORD> }); await trx('profile').insert({ avatar, user_id: user[0] }); await trx.commit(); const token = jwt.sign({ id: user[0] }, String(process.env.JWT_REGISTER), { expiresIn: '24h', }) const link = `http://localhost:3000/confirm/${token}`; const content = ` <p>Thank you for registering an account for Proffy πŸ’œ! Before entering your account, we need to confirm if it's really you! Click below to verify your e-mail</p> <p>This link is valid for 24 hours, once it expires, you can register again to receive this e-mail again.</p> <a href=${link} target="_blank" style="margin-top: 20px; display: block; text-decoration: none; border: none; background: #916BEA; border-radius: 0.8rem; color: white; padding: 15px 30px;">Verify!</a> ` sendMail(email, 'E-mail verification from Proffy', content, `Thank you for registering an account for Proffy πŸ’œ! Before entering your account, we need to confirm if it's really you! Click below to verify your e-mail ${link}`); return rsp.status(201).send({ id: user[0] }); } catch (error) { console.log(error) rsp.status(500).send({ message: error }); } } async confirm(rq: Request, rsp: Response, next: NextFunction) { const { token } = rq.params; if (!token) return rsp.status(401).send({ message: 'No token provided' }); jwt.verify(token, String(process.env.JWT_REGISTER), async (err: any, decoded: any) => { if (err) return rsp.status(401).send({ message: 'Invalid token' }); const trx = await db.transaction(); await trx('users').where('id', '=', decoded.id).update({ confirmed: true }); await trx.commit(); }); return rsp.status(202).send({ message: 'E-mail confirmed. You can now log in.' }); } async forgot(rq: Request, rsp: Response) { const { email } = rq.body; const user = await db('users').where('email', '=', email); if (user.length == 0) return rsp.status(400).send({ message: 'E-mail not found' }); const token = jwt.sign({ email: user[0].email }, String(process.env.JWT_REGISTER), { expiresIn: '1h', }); const appLink = 'http://localhost:3000/reset-password/' const content = ` <p>Are you trying to access into your account and forgot your password? If so, here is the link to reset it, its only valid for <b>1 hour</b>:<br> <a target="_blank" href=${appLink+token} style="margin: 20px 0; display: block; text-decoration: none; border: none; background: #916BEA; border-radius: 0.8rem; color: white; padding: 15px 30px;">Reset my password!</a></p> <p>If you are not trying to reset your password, just ignore it.</p> ` sendMail(email, 'Forgot your password?', content, `Are you trying to access into your account and forgot your password? If so, here is the link to reset it, its only valid for 1 hour: ${appLink+token}`); console.log(token) return rsp.status(200).send({ message: 'E-mail sent.' }); } async reset(rq: Request, rsp: Response) { const { password, token } = rq.body; jwt.verify(token, String(process.env.JWT_REGISTER), async (err: any, decoded: any) => { if (err) return rsp.status(401).send({ message: 'Invalid token' }); const currentPass = await db('users').where('email', '=', decoded.email).select('users.password'); const passwordCompare = await bcrypt.compare(password, currentPass[0].password); if (passwordCompare) { return rsp.status(401).send({ message: 'Make sure to use a different password!' }); } const salt = await bcrypt.genSalt(10); const hashedPassword = await bcrypt.hash(password, salt); const trx = await db.transaction(); await trx('users').where('email', '=', decoded.email).update({ password: hashedPassword }); await trx.commit(); return rsp.status(200).send({ message: 'Password reset went successfully.' }) }); } async authenticate(rq: Request, rsp: Response) { const { email, password, remember_me } = rq.body; const user = await db('users').where('email', '=', email); if (user.length == 0) return rsp.status(400).send({ message: 'Login failed' }) // email const passwordCompare = await bcrypt.compare(password, user[0].password); if (!passwordCompare) return rsp.status(400).send({ message: 'Login failed' }) // password if (!user[0].confirmed) return rsp.status(400).send({ message: 'You must confirm your e-mail.' }) // email not confirmed let accessToken = 'Proff '; if (remember_me) { accessToken += jwt.sign({ id: user[0].id }, String(process.env.JWT_AUTH), { expiresIn: '7d', }); } else { accessToken += jwt.sign({ id: user[0].id }, String(process.env.JWT_AUTH), { expiresIn: '12h', }); } const info = await db('users') .join('profile', 'users.id', 'profile.user_id') .select(['users.*', 'profile.*']) .where({ user_id: user[0].id }); const totalConnections = await db('connections').where('user_id', '=', user[0].id).count('* as total'); info[0] = { ...info[0], password: <PASSWORD>, user_id: undefined, confirmed: undefined, total_connections: totalConnections[0].total } rsp.cookie('__bruh', accessToken, { httpOnly: true }) return rsp.status(202).send(info[0]); } async verify(rq: Request, rsp: Response) { const user = await db('users') .join('profile', 'users.id', 'profile.user_id') .select(['users.*', 'profile.*']) .where({ user_id: rq.userId }); if (user.length == 0) { return rsp.status(400).send({ message: 'Invalid Id' }) } const totalConnections = await db('connections').where('user_id', '=', rq.userId).count('* as total'); user[0] = { ...user[0], password: <PASSWORD>, user_id: undefined, total_connections: totalConnections[0].total } return rsp.status(200).send({ ...user[0] }); } async logout(rq: Request, rsp: Response) { rsp.cookie('__bruh', null, { httpOnly: true, maxAge: 0 }) return rsp.send({ message: 'Logged out' }) } async remove(rq: Request, rsp: Response) { const { password } = rq.body; const user = await db('users').where('id', '=', rq.userId); if (user.length == 0) return rsp.status(400).send({ message: 'Invalid user' }) const passwordCompare = await bcrypt.compare(password, user[0].password); if (!passwordCompare) return rsp.status(400).send({ message: 'Invalid password' }) const trx = await db.transaction(); await trx('users').where('id', '=', rq.userId).delete(); await trx.commit(); return rsp.send(); } async index(rq: Request, rsp: Response) { const { id } = rq.params; try { const user = await db('users') .join('profile', 'users.id', 'profile.user_id') .select('users.*', 'profile.*') .where('profile.user_id', '=', id); if (user.length == 0) { return rsp.status(400).send({ message: 'Invalid Id' }) } // total connections user got over students const totalConnections = await db('connections').where('user_id', '=', id).count('* as total'); user[0] = { ...user[0], total_connections: totalConnections[0].total, email: undefined, password: <PASSWORD>, user_id: undefined, } return rsp.status(200).send({ ...user[0] }); } catch (error) { console.error(error) return rsp.status(400).send({ message: error }); } } }
EdRamos12/Proffy
server/src/routes.ts
<filename>server/src/routes.ts<gh_stars>1-10 import express from 'express'; import multer from 'multer'; import {celebrate, Joi, Segments} from 'celebrate'; import multerConfig from './config/multer'; import ClassesController from './controllers/ClassesController'; import ConnectionsController from './controllers/ConnectionsController'; import UserController from './controllers/UserController'; import ProfileController from './controllers/ProfileController'; import authMiddleware from './utils/auth'; import rateLimit from 'express-rate-limit'; import ClassCommentsController from './controllers/ClassCommentsController'; const routes = express.Router(); const upload = multer(multerConfig); const classesController = new ClassesController(); const connectionsController = new ConnectionsController(); const userController = new UserController(); const profileController = new ProfileController(); const classCommentsController = new ClassCommentsController(); const uploadLimiter = rateLimit({ windowMs: 15 * 60 * 1000, // 15 minutes max: 5, handler: (_, rsp) => { rsp.status(429).send({ message: 'You are being rate limited, please try again later.' }) } }); const classesListingLimiter = rateLimit({ windowMs: 45 * 60 * 1000, // 45 minutes max: 400, handler: (_, rsp) => { rsp.status(429).send({ message: 'You have seen too many classes, why not take a break? β˜•' }) } }); // TODO: some better system or amount of rate to replace // const verifyLimiter = rateLimit({ // windowMs: 15 * 60 * 1000, // 15 minutes // max: 1000, // handler: (_, rsp) => { // rsp.status(429).send({ message: 'You are being rate limited, please try again later.' }) // } // }); /////////////////////////////////////////////////////////////// routes.post('/register', celebrate({ [Segments.BODY]: Joi.object().keys({ name: Joi.string().required(), email: Joi.string().required().email(), password: Joi.string().required().min(8), }) }, {abortEarly: false}), userController.create); routes.post('/authenticate', celebrate({ [Segments.BODY]: Joi.object().keys({ email: Joi.string().required().email(), password: Joi.string().required(), remember_me: Joi.boolean().required(), }) }, {abortEarly: false}), userController.authenticate); routes.get('/verify', authMiddleware, userController.verify); routes.post('/forgot_password', celebrate({ [Segments.BODY]: Joi.object().keys({ email: Joi.string().required().email(), }) }, {abortEarly: false}), userController.forgot); routes.post('/reset_password', celebrate({ [Segments.BODY]: Joi.object().keys({ token: Joi.string().required(), password: <PASSWORD>().required().min(8), }) }, {abortEarly: false}), userController.reset); routes.get('/confirmation/:token', userController.confirm); routes.get('/logout', authMiddleware, userController.logout); routes.delete('/user/delete', authMiddleware, userController.remove); /////////////////////////////////////////////////////////////// routes.get('/profile/:id', authMiddleware, userController.index); routes.put('/profile', uploadLimiter, authMiddleware, upload.single('avatar'), celebrate({ [Segments.BODY]: Joi.object().keys({ whatsapp: Joi.string().optional(), bio: Joi.string().optional(), name: Joi.string().optional() }) }, {abortEarly: false}), profileController.edit); /////////////////////////////////////////////////////////////// routes.post('/classes', authMiddleware, classesController.create); routes.get('/total_classes', authMiddleware, classesController.total); routes.get('/total_classes/user/:user_id', authMiddleware, classesController.total_from_user); routes.get('/classes', classesListingLimiter, authMiddleware, classesController.index); routes.delete('/classes/:id', authMiddleware, classesController.delete); routes.put('/classes/:id', authMiddleware, classesController.edit); routes.get('/classes/:id', classesController.index_one); /////////////////////////////////////////////////////////////// routes.post('/classes/:class_id/comment', authMiddleware, celebrate({ [Segments.BODY]: Joi.object().keys({ content: Joi.string().required() //comment itself }) }, {abortEarly: false}), classCommentsController.create); routes.get('/classes/:class_id/comment', classCommentsController.index); routes.delete('/classes/:class_id/comment/:id', authMiddleware, classCommentsController.delete); /////////////////////////////////////////////////////////////// routes.post('/connections', authMiddleware, connectionsController.create); routes.get('/connections', authMiddleware, connectionsController.index); export default routes;
EdRamos12/Proffy
web/src/components/Notification/index.tsx
<reponame>EdRamos12/Proffy import React, { useEffect, useState } from 'react'; import './styles.css'; interface NotificationProps { message: String; title: String; type: String; id: String; dispatch: any; } const NotificationComponent: React.FC<NotificationProps> = (props) => { const [exit, setExit] = useState(false); const [width, setWidth] = useState(0 as any); const [intervalID, setIntervalID] = useState(null as any); function handleStartTimer() { const interval = setInterval(() => { setWidth((prev: number) => { if (prev < 100) { return prev + .5; } clearInterval(interval); return prev; }); }, 20); setIntervalID(interval); } function handlePauseTimer() { clearInterval(intervalID); } function handleClose() { handlePauseTimer(); setExit(true); setTimeout(() => { props.dispatch({ type: "REMOVE_NOTIFICATION", id: props.id }) }, 350) } useEffect(() => { handleStartTimer(); }, []); useEffect(() => { if (width === 100) { handleClose(); } }, [width]) return ( <div onMouseEnter={handlePauseTimer} onMouseLeave={handleStartTimer} className={`notification ${props.type === 'SUCCESS' ? 'success' : 'error' } ${exit ? "exit" : ""}` }> <h1>{props.title}</h1> <p>{props.message}</p> <div className="bar" style={{width: `${width}%`}}></div> </div> ); } export default NotificationComponent;
EdRamos12/Proffy
server/src/config/multer.ts
<reponame>EdRamos12/Proffy import multer from 'multer'; import path from 'path'; import crypto from 'crypto'; export default { storage: multer.diskStorage({ destination: path.join(__dirname, '..', '..', 'uploads'), filename: (r, file, callback) => { const hash = crypto.randomBytes(8).toString('hex'); const filename = `${hash}-${file.originalname}`; callback(null, filename); } }), limits: { fileSize: 5 * 1000 * 1000, }, fileFilter: function(rq: any, file: any, cb: any){ const fileTypes = /jpeg|jpg|png|gif|jfif/; const extName = fileTypes.test(path.extname(file.originalname).toLowerCase()); const mimeType = fileTypes.test(file.mimetype); if (mimeType && extName) { return cb(null, true); } cb('Error: Images only!'); } }
EdRamos12/Proffy
web/src/pages/Forgot/index.tsx
import React, { useState, FormEvent, useEffect } from 'react' import { Link } from 'react-router-dom'; import logoImg from '../../assets/images/logo.svg'; import backIcon from '../../assets/images/icons/back.svg' import SuccessContainer from '../../components/SuccessContainer'; import api from '../../services/api'; export default function Forgot () { const [success, setSuccess] = useState(false); const [error, setError] = useState(''); const [email, setEmail] = useState(''); async function handleForgotPass(e: FormEvent) { e.preventDefault(); try { await api.post('/forgot_password', { email }); setSuccess(true); } catch (error) { console.log({ error }) setError(error.response.data.message); } } useEffect(() => { setError(''); }, [email]) return ( <div id="register-page"> {success && <div id='register-success'> <SuccessContainer title="Redefinition sent!" success={success} button_text="Sign in!"> Instructions have been sent to your e-mail. <br /> The token expires in 1 hour. </SuccessContainer> </div>} <div id="register-page-content"> <Link to='/' id="go-back"> <img src={backIcon} alt="go back" /> </Link> <form onSubmit={handleForgotPass} id="register-form"> <fieldset> <div id="register-form-header"> <h1>Forgot my password</h1> <p id="description"> Do not worry, we can take care of it. </p> <span><strong>{error}</strong></span> </div> <div className="input-block" id="Email"> <label htmlFor="Email-input" id={Boolean(email) ? "active" : ""}>E-mail</label> <input required style={{borderRadius: '10px'}} className={Boolean(error) ? "input-error" : ""} type="email" id="Email-input" onChange={(e) => {setEmail(e.target.value)}} /> </div> <button type="submit" disabled={!Boolean(email)}> Send </button> </fieldset> </form> <div id="register-bg-container"> <div id="register-bg-items-container"> <div> <img src={logoImg} alt="Proffy"/> <h2>Your online platform <br /> to study.</h2> </div> </div> </div> </div> </div> ); }
DanRegazzi/DanRegazziProfile
src/components/header/Header.tsx
import { IonHeader, IonText } from "@ionic/react"; import * as React from "react"; import "./header.scss"; interface HeaderProps { page: string; } const Header: React.FC<HeaderProps> = (props) => ( <IonHeader> <IonText color="primary"><NAME></IonText> </IonHeader> ); export default Header;
DanRegazzi/DanRegazziProfile
src/components/header/index.ts
<filename>src/components/header/index.ts export {default as Header} from "./Header";
DanRegazzi/DanRegazziProfile
src/components/pages/home/index.ts
<reponame>DanRegazzi/DanRegazziProfile //import Home from './Home'; //export default Home; export {default as Home} from "./Home";
DanRegazzi/DanRegazziProfile
src/components/pages/home/Home.tsx
<reponame>DanRegazzi/DanRegazziProfile<filename>src/components/pages/home/Home.tsx import { IonCol, IonContent, IonGrid, IonPage, IonRow, IonText } from '@ionic/react'; import * as React from 'react'; import { RouteComponentProps } from 'react-router'; import { Header } from '../../header'; import "./home.scss"; interface HomePageProps extends RouteComponentProps<{}> {} const Home: React.FC<HomePageProps> = ({match, history}) => ( <IonPage className="home"> <Header page="home" /> <IonContent color="dark"> <div className="top-banner"> <IonGrid> <IonRow> <IonCol size="3"></IonCol> <IonCol size="6"> <IonText color="light"><h2><NAME> is moving and will return soon.</h2></IonText> </IonCol> <IonCol size="3"></IonCol> </IonRow> </IonGrid> </div> </IonContent> </IonPage> ); export default Home;
DanRegazzi/DanRegazziProfile
src/App.tsx
<gh_stars>0 import * as React from "react"; import { IonApp, IonHeader, IonRouterOutlet } from "@ionic/react"; import { IonReactRouter } from "@ionic/react-router"; import { Route } from "react-router-dom"; import "./App.scss"; /* Ionic CSS */ import "@ionic/react/css/core.css"; /* Basic CSS for apps built with Ionic */ import '@ionic/react/css/normalize.css'; import '@ionic/react/css/structure.css'; import '@ionic/react/css/typography.css'; /* Optional CSS utils that can be commented out */ import '@ionic/react/css/padding.css'; import '@ionic/react/css/float-elements.css'; import '@ionic/react/css/text-alignment.css'; import '@ionic/react/css/text-transformation.css'; import '@ionic/react/css/flex-utils.css'; import '@ionic/react/css/display.css'; /* Pages */ import { Home } from './components/pages/home'; const App: React.FC = () => ( <IonApp> <IonHeader> <NAME> </IonHeader> <IonReactRouter> <IonRouterOutlet> {/* <Route path="/" exact render={props => <Home {...props} />} /> */} <Route path="/" exact component={Home} /> </IonRouterOutlet> </IonReactRouter> </IonApp> ); export default App;
thomasmendez/personal-website
src/app/models/VrArProjects.ts
export class VrArProjects { public title:string; public description:string; public myTasks:Array<string>; public teamSize:number; public teamRoles:Array<string>; public tools:Array<string>; public projectDuration:string; public startDate:string; public endDate:string; public website:string; public image:string; public videoLink:string; public download:string; public note:string; public platforms: string; }
thomasmendez/personal-website
src/app/models/Work.ts
export class Work { public jobTitle:string; public company:string; public city:string; public state:string; public startDate:string; public endDate:string; public jobRole:string; public jobDuties:Array<String>; }
thomasmendez/personal-website
src/app/app-routing.module.ts
<filename>src/app/app-routing.module.ts import { NgModule } from '@angular/core'; import { Routes, RouterModule } from '@angular/router'; import { HomeComponent } from './components/pages/home/home.component'; import { WorkComponent } from './components/pages/work/work.component'; import { SkillsToolsComponent } from './components/pages/skills-tools/skills-tools.component'; import { SoftwareProjectsComponent } from './components/pages/software-projects/software-projects.component'; import { VrArProjectsComponent } from './components/pages/vr-ar-projects/vr-ar-projects.component'; const routes: Routes = [ { path: '', component: HomeComponent }, { path: 'work', component: WorkComponent }, { path: 'skills&tools', component: SkillsToolsComponent }, { path: 'projects', redirectTo: 'projects/software', pathMatch: 'full' }, { path: 'projects/software', component: SoftwareProjectsComponent }, { path: 'projects/vr-ar', component: VrArProjectsComponent } ]; @NgModule({ imports: [RouterModule.forRoot(routes)], exports: [RouterModule] }) export class AppRoutingModule { }
thomasmendez/personal-website
e2e/src/pages/app.home.ts
<filename>e2e/src/pages/app.home.ts import { browser, by, element, Locator, WebElement, ElementFinder, ElementArrayFinder } from 'protractor'; export class HomePage { navigateTo(): Promise<unknown> { return browser.get(browser.baseUrl) as Promise<unknown>; } // About Me getAboutMeHeader(): Promise<string> { return element(by.css('app-about-me')).$('.header').getText() as Promise<string>; } getAboutMeContent(): Promise<boolean> { return element(by.css('app-about-me')).$('.content').isPresent() as Promise<boolean>; } // Contact getContactHeader(): Promise<string> { return element(by.css('app-contact')).$('.header').getText() as Promise<string>; } getContactContent(): Promise<boolean> { return element(by.css('app-contact')).$('.content').isPresent() as Promise<boolean>; } }
thomasmendez/personal-website
src/app/models/Icon.ts
<filename>src/app/models/Icon.ts<gh_stars>0 export class Icon { private name: string; private fafa: string; private link: string; constructor(name: string, fafaIcon: string, link: string) { this.name = name; this.fafa = fafaIcon; this.link = link; } }
thomasmendez/personal-website
src/app/app.module.ts
<filename>src/app/app.module.ts<gh_stars>0 import { BrowserModule, Title } from '@angular/platform-browser'; import { NgModule } from '@angular/core'; import { AppRoutingModule } from './app-routing.module'; import { AppComponent } from './app.component'; import { NgbModule } from '@ng-bootstrap/ng-bootstrap'; import { NavbarComponent } from './components/navbar/navbar.component'; import { HomeComponent } from './components/pages/home/home.component'; import { TitleHeaderComponent } from './components/title-header/title-header.component'; import { AboutMeComponent } from './components/pages/home/about-me/about-me.component'; import { ContactComponent } from './components/pages/home/contact/contact.component'; import { WorkComponent } from './components/pages/work/work.component'; import { SkillsToolsComponent } from './components/pages/skills-tools/skills-tools.component'; import { SoftwareProjectsComponent } from './components/pages/software-projects/software-projects.component'; import { VrArProjectsComponent } from './components/pages/vr-ar-projects/vr-ar-projects.component'; import { FooterComponent } from './components/footer/footer.component'; @NgModule({ declarations: [ AppComponent, NavbarComponent, HomeComponent, TitleHeaderComponent, AboutMeComponent, ContactComponent, WorkComponent, SkillsToolsComponent, SoftwareProjectsComponent, VrArProjectsComponent, FooterComponent ], imports: [ BrowserModule, AppRoutingModule, NgbModule ], providers: [ Title ], bootstrap: [AppComponent] }) export class AppModule { }
thomasmendez/personal-website
e2e/src/pages/app.skills-tools.ts
<gh_stars>0 import { browser, by, element, Locator, WebElement, ElementFinder, ElementArrayFinder } from 'protractor'; export class SkillsAndToolsPage { navigateTo(): Promise<unknown> { return browser.get('/skills&tools') as Promise<unknown>; } // Skills getSkillsHeader(): Promise<string> { return element(by.css('app-skills-tools')).all(by.css('.header')).first().getText() as Promise<string>; } getSkillsContent(): Promise<number> { return element(by.css('app-skills-tools')).all(by.css('#content-skills li')).count() as Promise<number>; } // Tools getToolsHeader(): Promise<string> { return element(by.css('app-skills-tools')).all(by.css('.header')).last().getText() as Promise<string>; } getToolsContent(): Promise<number> { return element(by.css('app-skills-tools')).all(by.css('#content-tools li')).count() as Promise<number>; } }
thomasmendez/personal-website
src/app/components/pages/vr-ar-projects/vr-ar-projects.component.spec.ts
import { async, ComponentFixture, TestBed } from '@angular/core/testing'; import { RouterTestingModule } from '@angular/router/testing'; import { VrArProjectsComponent } from './vr-ar-projects.component'; import { CUSTOM_ELEMENTS_SCHEMA } from '@angular/core'; describe('VrArProjectsComponent', () => { let component: VrArProjectsComponent; let fixture: ComponentFixture<VrArProjectsComponent>; beforeEach(async(() => { TestBed.configureTestingModule({ imports: [ RouterTestingModule ], declarations: [ VrArProjectsComponent ], schemas: [ CUSTOM_ELEMENTS_SCHEMA ] }) .compileComponents(); })); beforeEach(() => { fixture = TestBed.createComponent(VrArProjectsComponent); component = fixture.componentInstance; fixture.detectChanges(); }); it('should create', () => { expect(component).toBeTruthy(); }); it('html should contain app-title-header', () => { const compiled = fixture.debugElement.nativeElement; expect(compiled.querySelector('app-title-header')).not.toBe(null); }) it("component should contain title 'Virtual Reality (VR) / Augmented Reality (AR) Projects'", () => { const projects = fixture.debugElement.componentInstance; expect(projects.title).toEqual('Virtual Reality (VR) / Augmented Reality (AR) Projects'); }) });
thomasmendez/personal-website
src/app/components/pages/work/work.component.ts
<reponame>thomasmendez/personal-website<gh_stars>0 import { Component, OnInit } from '@angular/core'; import { Work } from '../../../models/Work'; @Component({ selector: 'app-work', templateUrl: './work.component.html', styleUrls: ['./work.component.css'] }) export class WorkComponent implements OnInit { public title : string = "Where I Worked"; public jobs : Work[]; constructor() { } ngOnInit(): void { this.jobs = [ { jobTitle:"Software Engineer", company:"Surfboard", city:"Richardson", state:"Texas", startDate:"June 2019", endDate:"March 2020", jobRole:"Software Engineer / Mobile Augmented Reality Developer (Android & iOS)", jobDuties: [ "Prototyped persistent world-scale augmented reality using ARCore and ARKit", "Prototyped Instagram like gestures for 3D object/text manipulation in ARKit", "Designed and documented reusable modules for Android and iOS prototypes using MVC architecture", "Used unit and integration test for parts of the augmented reality prototype for Android and iOS", "Used agile methodology and rapid prototyping practices" ] }, { jobTitle:"Provisioning Automation for Oracle Cloud Infrastructure Intern​", company:"Accenture", city:"Irving", state:"Texas", startDate:"​June 2018", endDate:"Aug 2018", jobRole:"Support Analyst (DevOps Engineer Intern)", jobDuties: [ "Worked in the development of creating a provisioning tool using Terraform, APEX, and RESTful Services, which would drive the provisioning of resources in Oracle Cloud Infrastructure", "Created reusable Terraform modules for team use" ] }, { jobTitle:"Video Game Development for Research", company:"SAGA Lab", city:"Austin,", state:"Texas", startDate:"January 2018", endDate:"May 2018", jobRole:"#C Unity Programmer", jobDuties: [ "Modified an existing video game developed at the SAGA Lab to meet the needs for a research study at the university", "Re-programmed certain game scripts and created new 2D and 3D assets to fit the needs of the research" ] } ] } }
thomasmendez/personal-website
src/app/components/pages/skills-tools/skills-tools.component.ts
import { Component, OnInit } from '@angular/core'; @Component({ selector: 'app-skills-tools', templateUrl: './skills-tools.component.html', styleUrls: ['./skills-tools.component.css'] }) export class SkillsToolsComponent implements OnInit { public title : string = "Skills & Tools" public keepOriginalOrder = (a, b) => a.key public skills: {[key:string]:Array<string>} public tools: {[key:string]:Array<string>} constructor() { } ngOnInit(): void { this.skills = { "Trilingual":["English", " Spanish", " Portuguese"], "Software Methodologies and Practices":["Agile", " Scrum", " Rapid Prototyping"], "Design Thinking":["IBM Enterprise Design Thinking"] } this.tools = { "Game Engines": ["Unity"], "Programming Languages": ["Python", " C#", " Swift", " Java"], "Front-End": ["HTML", " CSS", " Javascript", " ES6", " React.js", " Webpack", " Babel", " Angular", " Bootstrap", " Pug"], "Back-End": ["Node.js", " PHP", " Flask", " SQLAlchemy"], "Databases": ["MySQL", " PL/SQL", " Postgres", " MongoDB"], "Mobile Development": ["iOS (XCode)", " Android (Android Studio)"], "Unit Testing": [ "unittest (Python)", " Mocha", " Jasmine", " Chai", " Enzyme", " Junit", " XCTest"], "CI/CD Tools": ["Jenkins", " Gitlab CI", " Github Actions", " Docker"], "Data Mining": ["Classification", " Clustering", " Association Analysis", " Dimensionality Reduction"], "OS": [ "Windows", " macOS", " Linux (Ubuntu)"] } } }
thomasmendez/personal-website
src/app/components/pages/software-projects/software-projects.component.ts
import { Component, OnInit } from '@angular/core'; import { SoftwareProjects } from '../../../models/SoftwareProjects'; @Component({ selector: 'app-software-projects', templateUrl: './software-projects.component.html', styleUrls: ['./software-projects.component.css'] }) export class SoftwareProjectsComponent implements OnInit { public title : string = "Software Engineering Projects"; public projects : SoftwareProjects[]; constructor() { } ngOnInit(): void { this.projects = [ { title:"Open-LMS-Blended", description:"An open source learning management system intended for K-12 educational institutions.", myTasks:[ "Developed an open source LMS intended for K-12 educational institutions using the MERN stack", "Experienced the entire development lifecycle, deployed, and documented the entire application for both Digital Ocean and AWS" ], teamSize:1, teamRoles:[], cloudServices:[ "AWS", " Digital Ocean" ], tools:[ "MongoDB", " Express", " React.js", " Node.js" ], projectDuration:"3 Months", startDate:"March 2020", endDate:"May 2020", repository:"https://github.com/thomasmendez/open-lms-blended", website:"https://open-lms-blended.org/", image:"", videoLink:"assets/open-lms-blended-sample.mp4", note:"" }, { title:"Noble Prizes Website", description:"Dynamic website that shows information about different laureates, countries that they are from, and different noble prize categories they won.", myTasks:[ "Create a dynamic website showcasing all the laureates, their awards, and their country of origin with a team of 5", "Worked with SQLAlchemy and the Google Cloud Platform to make sure webpages were deployed properly", "Developed static pages using HTML and CSS" ], teamSize:5, teamRoles:[ "Front-End Development", "Back-End Development", "Unit Testing and Continous Integration", "GCP Deployment" ], cloudServices:[ "Google Cloud Platform" ], tools:[ "HTML", " CSS", " Bootstrap", " Javascript", " Flask", " SQL Alchemy", " Postgres" ], projectDuration:"7 Weeks", startDate:"10/14/2018", endDate:"12/02/2018", repository:"https://gitlab.com/thomasmendez/cs329e-idb", website:"", image:"assets/laureates.png", videoLink:"", note:"Website currently not running because of the expensive cost of App Engine" }, { title:"Custom Clothing Brand Website", description:"Dynamic clothing brand website that allows users to browse the brand's selection of products. Users can interact with the website to place orders, contact the brand, add products to their cart, and see all products available through a database.", myTasks:[ "Worked with another full-stack developer to create a potential website for a future clothing brand", "Used the LAMP (Linux-Apache-MySQL-PHP) stack to develop the application" ], teamSize:2, teamRoles:[ "Full-Stack Development" ], cloudServices:[ ], tools:[ "HTML", " CSS", " Bootstrap", " Javascript", " Linux", " Apache", " MySQL", " PHP" ], projectDuration:"8 Weeks", startDate:"10/24/2018", endDate:"12/12/2018", repository:"", website:"", image:"assets/lcm.png", videoLink:"", note:"Website no longer avaliable since July 2020" } ] } }
thomasmendez/personal-website
src/app/components/pages/software-projects/software-projects.component.spec.ts
<filename>src/app/components/pages/software-projects/software-projects.component.spec.ts<gh_stars>0 import { async, ComponentFixture, TestBed } from '@angular/core/testing'; import { RouterTestingModule } from '@angular/router/testing'; import { SoftwareProjectsComponent } from './software-projects.component'; import { CUSTOM_ELEMENTS_SCHEMA } from '@angular/core'; describe('SoftwareProjectsComponent', () => { let component: SoftwareProjectsComponent; let fixture: ComponentFixture<SoftwareProjectsComponent>; beforeEach(async(() => { TestBed.configureTestingModule({ imports: [ RouterTestingModule ], declarations: [ SoftwareProjectsComponent ], schemas: [ CUSTOM_ELEMENTS_SCHEMA ] }) .compileComponents(); })); beforeEach(() => { fixture = TestBed.createComponent(SoftwareProjectsComponent); component = fixture.componentInstance; fixture.detectChanges(); }); it('should create', () => { expect(component).toBeTruthy(); }); it('html should contain app-title-header', () => { const compiled = fixture.debugElement.nativeElement; expect(compiled.querySelector('app-title-header')).not.toBe(null); }) it("component should contain title 'Software Engineering Projects'", () => { const projects = fixture.debugElement.componentInstance; expect(projects.title).toEqual('Software Engineering Projects'); }) });
thomasmendez/personal-website
src/app/components/footer/footer.component.ts
<gh_stars>0 import { Component, OnInit } from '@angular/core'; import { Icon } from '../../models/Icon'; import { MyInfo } from '../../static/MyInfo'; @Component({ selector: 'app-footer', templateUrl: './footer.component.html', styleUrls: ['./footer.component.css'] }) export class FooterComponent implements OnInit { public current_year: number; public icons: Icon[]; constructor() { } ngOnInit(): void { this.current_year = new Date().getFullYear(); this.icons = MyInfo.myIcons; } }
thomasmendez/personal-website
e2e/src/pages/app.vr-ar-projects.ts
<reponame>thomasmendez/personal-website import { browser, by, element, Locator, WebElement, ElementFinder, ElementArrayFinder } from 'protractor'; export class VrArProjects { navigateTo(): Promise<unknown> { return browser.get('/projects/vr-ar') as Promise<unknown>; } // VR / AR Projects getProjectHeader(): Promise<string> { return element(by.css('app-vr-ar-projects')).all(by.css('.header')).first().getText() as Promise<string>; } getSkillsContent(): Promise<number> { return element(by.css('app-vr-ar-projects')).all(by.css('.mytasks li')).count() as Promise<number>; } }
thomasmendez/personal-website
src/app/app-routing.spec.ts
import { TestBed, async } from '@angular/core/testing'; import { RouterTestingModule } from '@angular/router/testing'; import { Router, RouterModule } from '@angular/router'; import { AppComponent } from './app.component'; import { CUSTOM_ELEMENTS_SCHEMA } from '@angular/core'; describe('AppRouting', () => { beforeEach(async(() => { TestBed.configureTestingModule({ imports: [ RouterTestingModule, RouterModule ], declarations: [ AppComponent ], schemas: [ CUSTOM_ELEMENTS_SCHEMA ] }).compileComponents(); })); it('should navigate to home', () => { const fixture = TestBed.createComponent(AppComponent); const router = TestBed.get(Router); const navigateSpy = spyOn(router, 'navigate'); router.navigate(['/']) expect(navigateSpy).toHaveBeenCalledWith(['/']); }); it('should navigate to work', () => { const fixture = TestBed.createComponent(AppComponent); const router = TestBed.get(Router); const navigateSpy = spyOn(router, 'navigate'); router.navigate(['/work']) expect(navigateSpy).toHaveBeenCalledWith(['/work']); }); it('should navigate to skills & tools', () => { const fixture = TestBed.createComponent(AppComponent); const router = TestBed.get(Router); const navigateSpy = spyOn(router, 'navigate'); router.navigate(['/skills&tools']) expect(navigateSpy).toHaveBeenCalledWith(['/skills&tools']); }); it('should navigate to software projects', () => { const fixture = TestBed.createComponent(AppComponent); const router = TestBed.get(Router); const navigateSpy = spyOn(router, 'navigate'); router.navigate(['/projects/software']) expect(navigateSpy).toHaveBeenCalledWith(['/projects/software']); }); it('should navigate to software projects', () => { const fixture = TestBed.createComponent(AppComponent); const router = TestBed.get(Router); const navigateSpy = spyOn(router, 'navigate'); router.navigate(['/projects/vr-ar']) expect(navigateSpy).toHaveBeenCalledWith(['/projects/vr-ar']); }); });
thomasmendez/personal-website
e2e/src/app.e2e-spec.ts
<reponame>thomasmendez/personal-website import { HomePage } from './pages/app.home'; import { SkillsAndToolsPage } from './pages/app.skills-tools'; import { SoftwareProjects } from './pages/app.software-projects'; import { VrArProjects } from './pages/app.vr-ar-projects'; import { browser, logging } from 'protractor'; describe('workspace-project App', () => { let home: HomePage; let skills_tools: SkillsAndToolsPage; let software_projects: SoftwareProjects; let vr_ar_projects: VrArProjects; beforeEach(() => { home = new HomePage(); skills_tools = new SkillsAndToolsPage(); software_projects = new SoftwareProjects(); vr_ar_projects = new VrArProjects(); }); it('should have a About Me', () => { home.navigateTo(); expect(home.getAboutMeHeader()).toEqual('About Me'); expect(home.getAboutMeContent()).toBeTruthy(); // must contain a div for .content }) it('should have a Contact', () => { home.navigateTo(); expect(home.getContactHeader()).toEqual('Contact'); expect(home.getContactContent()).toBeTruthy(); // must contain div for .content }) it('should have Skills', () => { skills_tools.navigateTo(); expect(skills_tools.getSkillsHeader()).toEqual('Skills'); expect(skills_tools.getSkillsContent()).toBe(3); // li of skills is 3 }) it('should have Tools', () => { skills_tools.navigateTo(); expect(skills_tools.getToolsHeader()).toEqual('Tools'); expect(skills_tools.getToolsContent()).toBe(10); // li of tools is 10 }) it('should have Software Projects', () => { software_projects.navigateTo(); expect(software_projects.getProjectHeader()).toBeTruthy(); expect(software_projects.getSkillsContent()).toBeGreaterThan(0); }) it('should have VR / AR Projects', () => { vr_ar_projects.navigateTo(); expect(vr_ar_projects.getProjectHeader()).toBeTruthy(); expect(vr_ar_projects.getSkillsContent()).toBeGreaterThan(0); }) afterEach(async () => { // Assert that there are no errors emitted from the browser const logs = await browser.manage().logs().get(logging.Type.BROWSER); expect(logs).not.toContain(jasmine.objectContaining({ level: logging.Level.SEVERE, } as logging.Entry)); }); });
thomasmendez/personal-website
src/app/components/pages/home/contact/contact.component.spec.ts
import { async, ComponentFixture, TestBed } from '@angular/core/testing'; import { RouterTestingModule } from '@angular/router/testing'; import { ContactComponent } from './contact.component'; import { CUSTOM_ELEMENTS_SCHEMA } from '@angular/core'; describe('ContactComponent', () => { let component: ContactComponent; let fixture: ComponentFixture<ContactComponent>; beforeEach(async(() => { TestBed.configureTestingModule({ imports: [ RouterTestingModule ], declarations: [ ContactComponent ], schemas: [ CUSTOM_ELEMENTS_SCHEMA ] }) .compileComponents(); })); beforeEach(() => { fixture = TestBed.createComponent(ContactComponent); component = fixture.componentInstance; fixture.detectChanges(); }); it('should create', () => { expect(component).toBeTruthy(); }); it('should have an array of icons greater than length of 0', () => { expect(fixture.componentInstance.icons.length).toBeGreaterThan(0); }); });
thomasmendez/personal-website
src/app/components/footer/footer.component.spec.ts
<gh_stars>0 import { async, ComponentFixture, TestBed } from '@angular/core/testing'; import { FooterComponent } from './footer.component'; import { By } from '@angular/platform-browser'; describe('FooterComponent', () => { let component: FooterComponent; let fixture: ComponentFixture<FooterComponent>; beforeEach(async(() => { TestBed.configureTestingModule({ declarations: [ FooterComponent ] }) .compileComponents(); })); beforeEach(() => { fixture = TestBed.createComponent(FooterComponent); component = fixture.componentInstance; fixture.detectChanges(); }); it('should create', () => { expect(component).toBeTruthy(); }); it('should have footer html tag', () => { let de = fixture.debugElement; expect(de.query(By.css('footer'))).toBeTruthy(); }) it('should have copyright with current year', () => { let current_year = new Date().getFullYear(); let text = 'Β© ' + current_year + ' Copyright'; let de = fixture.debugElement; expect(de.query(By.css('.copyright')).nativeElement.innerHTML).toBe(text) }); it('should have an array of icons greater than length of 0', () => { expect(fixture.componentInstance.icons.length).toBeGreaterThan(0); }); });
thomasmendez/personal-website
e2e/src/pages/app.software-projects.ts
<reponame>thomasmendez/personal-website<filename>e2e/src/pages/app.software-projects.ts import { browser, by, element, Locator, WebElement, ElementFinder, ElementArrayFinder } from 'protractor'; export class SoftwareProjects { navigateTo(): Promise<unknown> { return browser.get('/projects/software') as Promise<unknown>; } // Software Engineering Projects getProjectHeader(): Promise<string> { return element(by.css('app-software-projects')).all(by.css('.header')).first().getText() as Promise<string>; } getSkillsContent(): Promise<number> { return element(by.css('app-software-projects')).all(by.css('.mytasks li')).count() as Promise<number>; } }
thomasmendez/personal-website
src/app/static/MyInfo.ts
import { Icon } from '../models/Icon'; export class MyInfo { public static myIcons: Icon[] = [MyInfo.linkedIn(), MyInfo.github(), MyInfo.email()] private static linkedIn(): Icon { let icon = new Icon('LinkedIn', 'fa fa-linkedin-square', "https://www.linkedin.com/in/thomas-a-mendez") return icon } private static github(): Icon { let icon = new Icon('Github', 'fa fa-github', "https://github.com/thomasmendez") return icon } private static email(): Icon { let icon = new Icon('Email', 'fa fa-envelope-square', "mailto:<EMAIL>") return icon } }
thomasmendez/personal-website
src/app/components/pages/vr-ar-projects/vr-ar-projects.component.ts
import { Component, OnInit } from '@angular/core'; import { VrArProjects } from '../../../models/VrArProjects'; @Component({ selector: 'app-vr-ar-projects', templateUrl: './vr-ar-projects.component.html', styleUrls: ['./vr-ar-projects.component.css'] }) export class VrArProjectsComponent implements OnInit { public title : string = "Virtual Reality (VR) / Augmented Reality (AR) Projects"; public projects : VrArProjects[] constructor() { } ngOnInit(): void { this.projects = [ { title:'Ankhor (Room Scale VR Game)', description:'A room scale mystery / horror game where you are a doctor trapped in a hospital with strange robed beings. You are able to interact with your surroundings in VR, pick up mysterious objects to aid you in your escape, and you must stealthily avoid getting captured.', myTasks:[ 'Develop VR Game Mechanics and Interactions' ], teamSize:6, teamRoles:[ '3 #C Unity Developers', '2 3D Modelers', '1 Game Designer', '1 Music Producer' ], tools:[ 'Unity', ' SteamVR Plugin', ' HTC Vive' ], projectDuration:'15 Weeks', startDate:'1/28/2019', endDate:'5/14/2019', website:'', image:'', videoLink:'assets/ankhor.mp4', download:'', note:'', platforms:'HTC Vive' }, { title:'MarkAR (AR Prototype)', description:'An augmented reality application intended to show the user where they place down a certain 3D object (marker) in the real world. They can then find it later and be directed to where they placed it.', myTasks:[ 'Develop Entire AR App Functionality' ], teamSize:3, teamRoles:[ 'C# Programmer', '2D Artist', '3D Modeler' ], tools:[ 'Unity', ' Google Pixel' ], projectDuration:'15 Weeks', startDate:'9/3/2018', endDate:'12/18/2018', website:'https://socialar.weebly.com/', image:'', videoLink:'assets/markar.mp4', download:'', note:'', platforms:'Andriod' }, { title:'Curffleboard (AR Game)', description:'An augmented reality game that allows users to play a game of curling using augmented reality technology. The game can be shared between two players with one phone.', myTasks:[ 'Create Win / Lose Conditions', 'Develop 2 Player Functionality' ], teamSize:3, teamRoles:[ 'C# Programmer', '2D Artist', '3D Modeler' ], tools:[ 'Unity', ' Google Pixel' ], projectDuration:'6 Weeks', startDate:'3/19/2018', endDate:'5/1/2018', website:'', image:'', videoLink:'assets/curffleboard.mp4', download:'https://utexas.app.box.com/v/CurffleboardApk', note:'', platforms:'Android' }, { title:'Tough Crowd (Room Scale VR Game)', description:'You are a bad comedian on stage and you are trying to avoid objects that the audience throws at you. You have to hold off the crowd until your crew closes the curtains for the stage.', myTasks:[ 'Develop VR Game Mechanics and Interactions', 'Created, Rigged, and Animated Enemies' ], teamSize:3, teamRoles:[ '2 C# Programmers', '3D Modeler' ], tools:[ 'Unity', ' SteamVR Plugin', ' HTC Vive' ], projectDuration:'5 Weeks', startDate:'2/13/2018', endDate:'3/19/2018', website:'', image:'', videoLink:'assets/toughcrowd.mp4', download:'https://utexas.app.box.com/s/d4zsulbdt0sxgd4jv8h7civgbcqvtsz5', note:'', platforms:'HTC Vive' } ] } }
thomasmendez/personal-website
src/app/components/title-header/title-header.component.spec.ts
<reponame>thomasmendez/personal-website import { async, ComponentFixture, TestBed } from '@angular/core/testing'; import { RouterTestingModule } from '@angular/router/testing'; import { TitleHeaderComponent } from './title-header.component'; import { CUSTOM_ELEMENTS_SCHEMA } from '@angular/core'; describe('TitleHeaderComponent', () => { let component: TitleHeaderComponent; let fixture: ComponentFixture<TitleHeaderComponent>; beforeEach(async(() => { TestBed.configureTestingModule({ imports: [ RouterTestingModule ], declarations: [ TitleHeaderComponent ], schemas: [ CUSTOM_ELEMENTS_SCHEMA ] }) .compileComponents(); })); beforeEach(() => { fixture = TestBed.createComponent(TitleHeaderComponent); component = fixture.componentInstance; fixture.detectChanges(); }); it('should create', () => { expect(component).toBeTruthy(); }); it('component should have a string for image variable', () => { const header = fixture.debugElement.componentInstance; expect(header.image).toEqual('assets/pic.jpeg'); }) });
thomasmendez/personal-website
src/app/components/title-header/title-header.component.ts
<filename>src/app/components/title-header/title-header.component.ts import { Component, OnInit, Input } from '@angular/core'; @Component({ selector: 'app-title-header', templateUrl: './title-header.component.html', styleUrls: ['./title-header.component.css'] }) export class TitleHeaderComponent implements OnInit { @Input() public isHome : boolean @Input() public title : string public image : string constructor() { } ngOnInit(): void { this.image = "assets/pic.jpeg" } }
thomasmendez/personal-website
src/app/components/pages/skills-tools/skills-tools.component.spec.ts
<reponame>thomasmendez/personal-website import { async, ComponentFixture, TestBed } from '@angular/core/testing'; import { RouterTestingModule } from '@angular/router/testing'; import { SkillsToolsComponent } from './skills-tools.component'; import { CUSTOM_ELEMENTS_SCHEMA } from '@angular/core'; describe('SkillsToolsComponent', () => { let component: SkillsToolsComponent; let fixture: ComponentFixture<SkillsToolsComponent>; beforeEach(async(() => { TestBed.configureTestingModule({ imports: [ RouterTestingModule ], declarations: [ SkillsToolsComponent ], schemas: [ CUSTOM_ELEMENTS_SCHEMA ] }) .compileComponents(); })); beforeEach(() => { fixture = TestBed.createComponent(SkillsToolsComponent); component = fixture.componentInstance; fixture.detectChanges(); }); it('should create', () => { expect(component).toBeTruthy(); }); it('should contain title header', () => { const compiled = fixture.debugElement.nativeElement; expect(compiled.querySelector('app-title-header')).not.toBe(null); }) });
cyber-republic/elastos-helloworld-app
trinity_app/src/pages/home/home.ts
<filename>trinity_app/src/pages/home/home.ts import { Component } from '@angular/core'; import { NavController } from 'ionic-angular'; declare let require_test: any; declare let cordova: any; @Component({ selector: 'page-home', templateUrl: 'home.html' }) export class HomePage { carpath = "libElastos.HelloCarDemo.so"; constructor(public navCtrl: NavController) { let type = this.GetQueryString("type"); switch (type) { case "payment": this.carpath = this.GetQueryString("txId"); break; case "did_login": this.carpath = this.GetQueryString("didNum"); break; default: this.carpath = "libElastos.HelloCarDemo.so";; break; } } GetQueryString(name){ var reg = new RegExp("(^|&)"+ name +"=([^&]*)(&|$)"); var r = window.location.search.substr(1).match(reg); if(r!=null)return decodeURI(r[2]); return null; } require_module(){ require_test(this.carpath); } require_DID(){ //console.log('Error: zhh ', "DATE require_wallet" ); cordova.plugins.appmanager.StartApp("wallet/www/index.html" + "?type=did_login&message=this is did login message&backurl=helloworld/www/index.html", function (data) { }, function (error) { }); } require_pay(){ //console.log('Error: zhh ', "DATE require_wallet" ); cordova.plugins.appmanager.StartApp("wallet/www/index.html" + "?type=payment&amount=10000&address=EeDUy6TmGSFfVxXVzMpVkxLhqwCqujE1WL&memo=chinajoylottery-f-EHmMW4UVLBkr6QB61CBexUQiXvFigvDJwi-fe5d57161eb78e0d3ff5d5a24398e9aea8914f71e762f06a49cd515b45d96af2&information=sss&backurl=helloworld/www/index.html", function (data) { }, function (error) { }); } }
redboul/ponyracer-ng2
src/app/models/user.model.ts
<gh_stars>0 export interface UserModel { id: number; login: string; money: number; registrationInstant: string; }
redboul/ponyracer-ng2
src/app/pony/pony.component.ts
import { Component, OnInit, Input, Output, EventEmitter } from '@angular/core'; import { PonyModel } from '../models/pony.model'; @Component({ selector: 'pr-pony', templateUrl: './pony.component.html', styleUrls: ['./pony.component.css'] }) export class PonyComponent implements OnInit { @Input() ponyModel: PonyModel; @Input() isRunning: boolean; @Output() ponyClicked = new EventEmitter<PonyModel>(); constructor() {} ngOnInit() { } getPonyImageUrl() { return `assets/images/pony-${this.ponyModel.color.toLowerCase()}${ this.isRunning ? '-running' : ''}.gif`; } clicked() { this.ponyClicked.emit(this.ponyModel); } }
redboul/ponyracer-ng2
src/app/home/home.component.ts
import { Component, OnInit, OnDestroy } from '@angular/core'; import { Subscription } from 'rxjs/Subscription'; import { UserModel } from '../models/user.model'; import { UserService } from '../user.service'; @Component({ selector: 'pr-home', templateUrl: './home.component.html', styleUrls: ['./home.component.css'] }) export class HomeComponent implements OnInit, OnDestroy { user: UserModel; userEventsSubscription: Subscription; constructor(private userService: UserService) { } ngOnInit() { this.userEventsSubscription = this.userService.userEvents.subscribe(user => this.user = user); } ngOnDestroy() { if (this.userEventsSubscription) { this.userEventsSubscription.unsubscribe(); } } }
redboul/ponyracer-ng2
src/app/app.component.spec.ts
import { TestBed } from '@angular/core/testing'; import { RouterTestingModule } from '@angular/router/testing'; import { AppModule } from './app.module'; import { AppComponent } from './app.component'; describe('AppComponent', () => { beforeEach(() => TestBed.configureTestingModule({ imports: [AppModule, RouterTestingModule] })); it('should have a title', () => { const fixture = TestBed.createComponent(AppComponent); const element = fixture.nativeElement; const routerOutlet = element.querySelector('router-outlet'); expect(routerOutlet).not.toBeNull('You need a RouterOutlet component in your root component'); }); });
redboul/ponyracer-ng2
src/app/register/register.component.ts
<reponame>redboul/ponyracer-ng2 import { Component, OnInit } from '@angular/core'; import { FormControl, FormGroup, FormBuilder, Validators } from '@angular/forms'; import { Router } from '@angular/router'; import { UserService } from '../user.service'; @Component({ selector: 'pr-register', templateUrl: './register.component.html', styleUrls: ['./register.component.css'] }) export class RegisterComponent implements OnInit { registrationFailed: boolean; loginCtrl: FormControl; passwordCtrl: FormControl; confirmPasswordCtrl: FormControl; birthYearCtrl: FormControl; userForm: FormGroup; passwordForm: FormGroup; static passwordMatch(control: FormGroup) { const password = control.get('password').value; const confirmPassword = control.get('confirmPassword').value; return password !== confirmPassword ? {matchingError: true} : null; } static validYear(control: FormControl) { const birthYear = control.value; return Number.isNaN(birthYear) || birthYear < 1900 || birthYear > new Date().getFullYear() ? {invalidYear: true} : null; } constructor(private fb: FormBuilder, private userService: UserService, private router: Router) { } ngOnInit() { this.loginCtrl = this.fb.control('', [Validators.required, Validators.minLength(3)]); this.passwordCtrl = this.fb.control('', Validators.required); this.confirmPasswordCtrl = this.fb.control('', Validators.required); this.passwordForm = this.fb.group({ password: <PASSWORD>, confirmPassword: this.confirm<PASSWORD> }, { validator: RegisterComponent.passwordMatch }); this.birthYearCtrl = this.fb.control('', [Validators.required, RegisterComponent.validYear]); this.userForm = this.fb.group({ login: this.loginCtrl, passwordForm: this.passwordForm, birthYear: this.birthYearCtrl }); } register() { this.userService.register( this.userForm.value.login, this.userForm.value.passwordForm.password, this.userForm.value.birthYear ).subscribe( () => this.router.navigate(['/']), () => this.registrationFailed = true ); } }
redboul/ponyracer-ng2
src/app/from-now.pipe.spec.ts
<filename>src/app/from-now.pipe.spec.ts import { FromNowPipe } from './from-now.pipe'; describe('FromNowPipe', () => { it('should transform the input', () => { // given a pipe const pipe = new FromNowPipe(); // when transforming the date const date = '2016-02-18T08:02:00Z'; const transformed = pipe.transform(date); // then we should have a formatted string expect(transformed).toContain('ago', 'The pipe should transform the date into a human string, using the `fromNow` method of Moment.js'); }); });
redboul/ponyracer-ng2
src/app/http.service.spec.ts
import { async, TestBed } from '@angular/core/testing'; import { Http, BaseRequestOptions, Response, ResponseOptions, RequestMethod } from '@angular/http'; import { MockBackend } from '@angular/http/testing'; import { HttpService } from './http.service'; describe('HttpService', () => { let httpService: HttpService; let mockBackend: MockBackend; beforeEach(() => TestBed.configureTestingModule({ providers: [ MockBackend, BaseRequestOptions, { provide: Http, useFactory: (backend, defaultOptions) => new Http(backend, defaultOptions), deps: [MockBackend, BaseRequestOptions] }, HttpService ] })); beforeEach(() => { httpService = TestBed.get(HttpService); mockBackend = TestBed.get(MockBackend); }); it('should init the service', () => { expect(httpService.baseUrl) .toBe('http://ponyracer.ninja-squad.com', 'Your service should have a field `baseUrl` correctly initialized'); expect(httpService.options.headers) .toBe(httpService.headers, 'Your service should have a field `options` correctly initialized with the headers'); }); it('should do a GET request', async(() => { const hardcodedRaces = [{ name: 'Paris' }, { name: 'Tokyo' }, { name: 'Lyon' }]; const response = new Response(new ResponseOptions({ body: hardcodedRaces })); // return the response if we have a connection to the MockBackend mockBackend.connections.subscribe(connection => { expect(connection.request.url) .toBe('http://ponyracer.ninja-squad.com/api/races?status=PENDING', 'The service should build the correct URL for a GET'); expect(connection.request.method).toBe(RequestMethod.Get); expect(connection.request.headers.get('Authorization')).toBeNull(); connection.mockRespond(response); }); httpService.get('/api/races?status=PENDING').subscribe((res) => { expect(res).toBe(hardcodedRaces); }); })); it('should do a POST request', async(() => { const user = { login: 'cedric' }; const response = new Response(new ResponseOptions({ body: user })); // return the response if we have a connection to the MockBackend mockBackend.connections.subscribe(connection => { expect(connection.request.url) .toBe('http://ponyracer.ninja-squad.com/api/users', 'The service should build the correct URL for a POST'); expect(connection.request.method).toBe(RequestMethod.Post); expect(connection.request.headers.get('Authorization')).toBeNull(); connection.mockRespond(response); }); httpService.post('/api/users', user).subscribe((res) => { expect(res).toBe(user); }); })); it('should add/remove the JWT token to the headers', () => { // will first return a 'secret' token, then nothing on second call let firstCall = true; spyOn(window.localStorage, 'getItem').and.callFake(() => { if (firstCall) { firstCall = false; return JSON.stringify({ token: 'secret' }); } return null; }); httpService.addJwtTokenIfExists(); // so we should have a header the first time expect(httpService.headers.get('Authorization')) .toBe('Bearer secret', 'The `Authorization` header is not correct after adding the JWT token'); httpService.addJwtTokenIfExists(); // and no header the second time expect(httpService.headers.get('Authorization')).toBeNull('The `Authorization` header should be null after removing the JWT token'); }); it('should do an authenticated GET request', async(() => { spyOn(window.localStorage, 'getItem') .and.returnValue(JSON.stringify({ token: 'secret' })); const hardcodedRaces = [{ name: 'Paris' }, { name: 'Tokyo' }, { name: 'Lyon' }]; const response = new Response(new ResponseOptions({ body: hardcodedRaces })); // return the response if we have a connection to the MockBackend mockBackend.connections.subscribe(connection => { expect(connection.request.url) .toBe('http://ponyracer.ninja-squad.com/api/races?status=PENDING'); expect(connection.request.method).toBe(RequestMethod.Get); expect(connection.request.headers.get('Authorization')).toBe('Bearer secret'); connection.mockRespond(response); }); httpService.get('/api/races?status=PENDING').subscribe((res) => { expect(res).toBe(hardcodedRaces); }); })); it('should do an authenticated DELETE request', async(() => { spyOn(window.localStorage, 'getItem') .and.returnValue(JSON.stringify({ token: 'secret' })); const response = new Response(new ResponseOptions({ status: 204 })); // return the response if we have a connection to the MockBackend mockBackend.connections.subscribe(connection => { expect(connection.request.url) .toBe('http://ponyracer.ninja-squad.com/api/races/1/bets'); expect(connection.request.method).toBe(RequestMethod.Delete); expect(connection.request.headers.get('Authorization')).toBe('Bearer secret'); connection.mockRespond(response); }); httpService.delete('/api/races/1/bets').subscribe((res) => { expect(res.status).toBe(204, 'The delete method should return the response (and not extract the JSON).'); }); })); });
redboul/ponyracer-ng2
src/app/live/live.component.ts
import { Component, OnInit, OnDestroy } from '@angular/core'; import { ActivatedRoute } from '@angular/router'; import { Subscription } from 'rxjs/Subscription'; import { RaceService } from '../race.service'; import { RaceModel } from '../models/race.model'; import { PonyWithPositionModel } from '../models/pony.model'; @Component({ selector: 'pr-live', templateUrl: './live.component.html', styleUrls: ['./live.component.css'] }) export class LiveComponent implements OnInit, OnDestroy { raceModel: RaceModel; poniesWithPosition: Array<PonyWithPositionModel>; positionSubscription: Subscription; constructor(private raceService: RaceService, private route: ActivatedRoute) { } ngOnInit() { const id = this.route.snapshot.params['raceId']; this.raceService.get(id).subscribe(race => this.raceModel = race); this.positionSubscription = this.raceService.live(id).subscribe(positions => this.poniesWithPosition = positions); } ngOnDestroy() { if (this.positionSubscription) { this.positionSubscription.unsubscribe(); } } }
redboul/ponyracer-ng2
src/app/bet/bet.component.ts
import { Component, OnInit } from '@angular/core'; import { ActivatedRoute } from '@angular/router'; import { RaceService } from '../race.service'; import { RaceModel } from '../models/race.model'; @Component({ selector: 'pr-bet', templateUrl: './bet.component.html', styleUrls: ['./bet.component.css'] }) export class BetComponent implements OnInit { raceModel: RaceModel; betFailed = false; constructor(private raceService: RaceService, private route: ActivatedRoute) { } ngOnInit() { const raceId = this.route.snapshot.params['raceId']; this.raceService.get(raceId) .subscribe(race => this.raceModel = race); } betOnPony(pony) { if (!this.isPonySelected(pony)) { this.raceService.bet(this.raceModel.id, pony.id) .subscribe(race => this.raceModel = race, () => this.betFailed = true); } else { this.raceService.cancelBet(this.raceModel.id) .subscribe(() => this.raceModel.betPonyId = null, () => this.betFailed = true); } } isPonySelected(pony) { return pony.id === this.raceModel.betPonyId; } }
redboul/ponyracer-ng2
src/app/login/login.component.ts
<reponame>redboul/ponyracer-ng2 import { Component, OnInit } from '@angular/core'; import { Router } from '@angular/router'; import { UserService } from '../user.service'; @Component({ selector: 'pr-login', templateUrl: './login.component.html', styleUrls: ['./login.component.css'] }) export class LoginComponent implements OnInit { credentials = { login: '', password: '' }; authenticationFailed = false; constructor(private router: Router, private userService: UserService) { } ngOnInit() { } authenticate() { this.authenticationFailed = false; this.userService.authenticate(this.credentials) .subscribe( () => this.router.navigate(['/']), () => this.authenticationFailed = true ); } }
redboul/ponyracer-ng2
src/app/login/login.component.spec.ts
import { async, TestBed } from '@angular/core/testing'; import { Router } from '@angular/router'; import { Subject } from 'rxjs/Subject'; import { AppModule } from '../app.module'; import { LoginComponent } from './login.component'; import { UserService } from '../user.service'; describe('LoginComponent', () => { const fakeRouter = jasmine.createSpyObj('Router', ['navigate']); const fakeUserService = jasmine.createSpyObj('UserService', ['authenticate']); beforeEach(() => TestBed.configureTestingModule({ imports: [AppModule], providers: [ { provide: UserService, useValue: fakeUserService }, { provide: Router, useValue: fakeRouter } ] })); beforeEach(() => { fakeRouter.navigate.calls.reset(); fakeUserService.authenticate.calls.reset(); }); it('should have a credentials field', () => { const fixture = TestBed.createComponent(LoginComponent); // when we trigger the change detection fixture.detectChanges(); // then we should have a field credentials const componentInstance = fixture.componentInstance; expect(componentInstance.credentials) .not.toBeNull('Your component should have a field `credentials` initialized with an object'); expect(componentInstance.credentials.login) .toBe('', 'The `login` field of `credentials` should be initialized with an empty string'); expect(componentInstance.credentials.password) .toBe('', 'The `password` field of `credentials` should be initialized with an empty string'); }); it('should have a title', () => { const fixture = TestBed.createComponent(LoginComponent); // when we trigger the change detection fixture.detectChanges(); // then we should have a title const element = fixture.nativeElement; expect(element.querySelector('h1')).not.toBeNull('The template should have a `h1` tag'); expect(element.querySelector('h1').textContent).toContain('Log in', 'The title should be `Log in`'); }); it('should have a disabled button if the form is incomplete', async(() => { const fixture = TestBed.createComponent(LoginComponent); // when we trigger the change detection fixture.detectChanges(); // then we should have a disabled button const element = fixture.nativeElement; fixture.whenStable().then(() => { fixture.detectChanges(); expect(element.querySelector('button')).not.toBeNull('The template should have a button'); expect(element.querySelector('button').hasAttribute('disabled')).toBe(true, 'The button should be disabled if the form is invalid'); }); })); it('should be possible to log in if the form is complete', async(() => { const fixture = TestBed.createComponent(LoginComponent); fixture.detectChanges(); const element = fixture.nativeElement; fixture.whenStable().then(() => { const loginInput = element.querySelector('input[name="login"]'); expect(loginInput).not.toBeNull('You should have an input with the name `login`'); loginInput.value = 'login'; loginInput.dispatchEvent(new Event('input')); const passwordInput = element.querySelector('input[name="password"]'); expect(passwordInput).not.toBeNull('You should have an input with the name `password`'); passwordInput.value = 'password'; passwordInput.dispatchEvent(new Event('input')); // when we trigger the change detection fixture.detectChanges(); // then we should have a submit button enabled expect(element.querySelector('button').hasAttribute('disabled')) .toBe(false, 'The button should be enabled if the form is valid'); }); })); it('should call the user service and redirect if success', () => { const fixture = TestBed.createComponent(LoginComponent); fixture.detectChanges(); const subject = new Subject(); fakeUserService.authenticate.and.returnValue(subject); const componentInstance = fixture.componentInstance; componentInstance.credentials.login = 'login'; componentInstance.credentials.password = 'password'; componentInstance.authenticate(); // then we should have called the user service method expect(fakeUserService.authenticate).toHaveBeenCalledWith({ login: 'login', password: 'password' }); subject.next(''); // and redirect to the home expect(componentInstance.authenticationFailed) .toBe(false, 'You should have a field `authenticationFailed` set to false if registration succeeded'); expect(fakeRouter.navigate).toHaveBeenCalledWith(['/']); }); it('should call the user service and display a message if failed', () => { const fixture = TestBed.createComponent(LoginComponent); fixture.detectChanges(); const subject = new Subject(); fakeUserService.authenticate.and.returnValue(subject); const componentInstance = fixture.componentInstance; componentInstance.credentials.login = 'login'; componentInstance.credentials.password = 'password'; componentInstance.authenticate(); // then we should have called the user service method expect(fakeUserService.authenticate).toHaveBeenCalledWith({ login: 'login', password: 'password' }); subject.error(new Error()); // and not redirect to the home expect(fakeRouter.navigate).not.toHaveBeenCalled(); expect(componentInstance.authenticationFailed) .toBe(true, 'You should have a field `authenticationFailed` set to true if registration failed'); }); it('should display a message if auth failed', () => { const fixture = TestBed.createComponent(LoginComponent); const componentInstance = fixture.componentInstance; componentInstance.authenticationFailed = true; fixture.detectChanges(); const element = fixture.nativeElement; expect(element.querySelector('.alert')).not.toBeNull('You should have a div with a class `alert` to display an error message'); expect(element.querySelector('.alert').textContent).toContain('Nope, try again'); }); });
redboul/ponyracer-ng2
src/app/live/live.component.spec.ts
import { TestBed } from '@angular/core/testing'; import { RouterTestingModule } from '@angular/router/testing'; import { ActivatedRoute } from '@angular/router'; import { By } from '@angular/platform-browser'; import { Observable } from 'rxjs/Observable'; import { AppModule } from '../app.module'; import { LiveComponent } from './live.component'; import { RaceService } from '../race.service'; import { PonyComponent } from '../pony/pony.component'; describe('LiveComponent', () => { const fakeRaceService = jasmine.createSpyObj('RaceService', ['get', 'live']); fakeRaceService.get.and.returnValue(Observable.of({ id: 1, name: 'Lyon', ponies: [], startInstant: '2016-02-18T08:02:00Z' })); fakeRaceService.live.and.returnValue(Observable.of([])); const fakeActivatedRoute = { snapshot: { params: { raceId: 1 } } }; beforeEach(() => TestBed.configureTestingModule({ imports: [AppModule, RouterTestingModule], providers: [ { provide: RaceService, useValue: fakeRaceService }, { provide: ActivatedRoute, useValue: fakeActivatedRoute } ] })); it('should display the title', () => { const fixture = TestBed.createComponent(LiveComponent); fixture.detectChanges(); const element = fixture.nativeElement; const title = element.querySelector('h2'); expect(title).not.toBeNull('The template should display an h2 element with the race name inside'); expect(title.textContent).toContain('Lyon', 'The template should display an h2 element with the race name inside'); }); it('should subscribe to the live observable', () => { const fixture = TestBed.createComponent(LiveComponent); fixture.detectChanges(); const liveComponent: LiveComponent = fixture.componentInstance; expect(fakeRaceService.live).toHaveBeenCalledWith(1); expect(liveComponent.poniesWithPosition).not.toBeNull('poniesWithPosition should be initialized in the subscribe'); expect(liveComponent.positionSubscription).not.toBeNull('positionSubscription should store the subscription'); }); it('should unsubscribe on destruction', () => { const fixture = TestBed.createComponent(LiveComponent); fixture.detectChanges(); const liveComponent: LiveComponent = fixture.componentInstance; spyOn(liveComponent.positionSubscription, 'unsubscribe'); liveComponent.ngOnDestroy(); expect(liveComponent.positionSubscription.unsubscribe).toHaveBeenCalled(); }); it('should display a div with a pony component per pony', () => { const fixture = TestBed.createComponent(LiveComponent); fixture.detectChanges(); const liveComponent: LiveComponent = fixture.componentInstance; liveComponent.poniesWithPosition = [ { id: 1, name: '<NAME>', color: 'BLUE', position: 10 }, { id: 2, name: '<NAME>', color: 'Green', position: 40 } ]; fixture.detectChanges(); const element = fixture.nativeElement; const divWithPonies = element.querySelectorAll('div.pony-wrapper'); expect(divWithPonies.length).toBe(2, 'You should display a `div` with a class `pony-wrapper` for each pony'); const debugElement = fixture.debugElement; const ponyComponents = debugElement.queryAll(By.directive(PonyComponent)); expect(ponyComponents).not.toBeNull('You should display a `PonyComponent` for each pony'); expect(ponyComponents.length).toBe(2, 'You should display a `PonyComponent` for each pony'); const sunnySunday = ponyComponents[0]; expect(sunnySunday.componentInstance.isRunning).toBeTruthy('Each pony should be running (use the `isRunning` input)'); const sunnySundayDiv = divWithPonies[0]; expect(sunnySundayDiv.getAttribute('style')).toBe('margin-left: 0%;', 'The `margin-left` style should match the pony\'s position in percent minus 10'); }); });
redboul/ponyracer-ng2
src/app/race.service.ts
import { Injectable } from '@angular/core'; import { Observable } from 'rxjs/Observable'; import 'rxjs/add/observable/interval'; import 'rxjs/add/operator/take'; import { RaceModel } from './models/race.model'; import { PonyWithPositionModel } from './models/pony.model'; import { HttpService } from './http.service'; import { WsService } from './ws.service'; @Injectable() export class RaceService { constructor(private http: HttpService, private ws: WsService) {} list(): Observable<Array<RaceModel>> { return this.http.get('/api/races?status=PENDING'); } get(raceId): Observable<RaceModel> { return this.http.get(`/api/races/${raceId}`); } bet(raceId, ponyId): Observable<RaceModel> { return this.http.post(`/api/races/${raceId}/bets`, { ponyId }); } cancelBet(raceId): Observable<any> { return this.http.delete(`/api/races/${raceId}/bets`); } live(raceId): Observable<Array<PonyWithPositionModel>> { return this.ws.connect(`/race/${raceId}`).map(body => body.ponies); } }
redboul/ponyracer-ng2
src/app/models/pony.model.ts
export interface PonyModel { id: number; name: string; color: string; } export interface PonyWithPositionModel extends PonyModel { position: number; }
redboul/ponyracer-ng2
src/app/user.service.ts
import { Injectable } from '@angular/core'; import { BehaviorSubject } from 'rxjs/BehaviorSubject'; import { Observable } from 'rxjs/Observable'; import 'rxjs/add/operator/map'; import 'rxjs/add/operator/do'; import { UserModel } from './models/user.model'; import { HttpService } from './http.service'; @Injectable() export class UserService { public userEvents = new BehaviorSubject<UserModel>(undefined); constructor(private http: HttpService) { this.retrieveUser(); } register(login, password, birthYear): Observable<UserModel> { return this.http.post('/api/users', {login, password, birthYear}); } authenticate(credentials): Observable<UserModel> { return this.http .post('/api/users/authentication', credentials) .do(user => this.storeLoggedInUser(user)); } storeLoggedInUser(user) { window.localStorage.setItem('rememberMe', JSON.stringify(user)); this.userEvents.next(user); } retrieveUser() { const value = window.localStorage.getItem('rememberMe'); if (value) { const user = JSON.parse(value); this.userEvents.next(user); } } logout() { this.userEvents.next(null); window.localStorage.removeItem('rememberMe'); } }
redboul/ponyracer-ng2
src/app/race/race.component.ts
<reponame>redboul/ponyracer-ng2 import { Component, OnInit, Input } from '@angular/core'; import { RaceModel } from '../models/race.model'; @Component({ selector: 'pr-race', templateUrl: './race.component.html', styleUrls: ['./race.component.css'] }) export class RaceComponent implements OnInit { @Input() raceModel: RaceModel; constructor() {} ngOnInit() { } }
redboul/ponyracer-ng2
src/app/app.routes.ts
import { Routes } from '@angular/router'; import { HomeComponent } from './home/home.component'; import { RacesComponent } from './races/races.component'; import { RegisterComponent } from './register/register.component'; import { LoginComponent } from './login/login.component'; import { BetComponent } from './bet/bet.component'; import { LiveComponent } from './live/live.component'; export const ROUTES: Routes = [ { path: '', component: HomeComponent }, { path: 'races', children: [ { path: '', component: RacesComponent }, { path: ':raceId', component: BetComponent }, { path: ':raceId/live', component: LiveComponent } ] }, { path: 'register', component: RegisterComponent }, { path: 'login', component: LoginComponent } ];
redboul/ponyracer-ng2
src/typings.d.ts
<filename>src/typings.d.ts // Typings reference file, you can add your own global typings here // https://www.typescriptlang.org/docs/handbook/writing-declaration-files.html declare module 'webstomp-client' { interface Webstomp { over(socketType: any): WebstompClient; } interface WebstompClient { connect(headers: {login: string; passcode: string}, connectCallback: () => any, errorCallback?: (error: any) => any); subscribe(destination: string, callback: (message: StompMessage) => any); } interface StompMessage { body: string; } let Webstomp: Webstomp; export = Webstomp; }
redboul/ponyracer-ng2
src/app/user.service.spec.ts
import { async, TestBed } from '@angular/core/testing'; import { Observable } from 'rxjs/Observable'; import { UserService } from './user.service'; import { HttpService } from './http.service'; describe('UserService', () => { let userService: UserService; const httpService = jasmine.createSpyObj('HttpService', ['post']); const user = { id: 1, login: 'cedric', money: 1000, registrationInstant: '2015-12-01T11:00:00Z', token: '<KEY>' }; beforeEach(() => TestBed.configureTestingModule({ providers: [ { provide: HttpService, useValue: httpService }, UserService ] })); beforeEach(() => userService = TestBed.get(UserService)); it('should register a user', async(() => { // fake response httpService.post.and.returnValue(Observable.of(user)); userService.register(user.login, 'password', 1986).subscribe(res => { expect(res.id).toBe(1, 'You should transform the Response into a user using the `json()` method.'); expect(httpService.post).toHaveBeenCalledWith('/api/users', { login: user.login, password: 'password', birthYear: 1986 }); }); })); it('should authenticate a user', async(() => { // fake response httpService.post.and.returnValue(Observable.of(user)); // spy on the store method spyOn(userService, 'storeLoggedInUser'); const credentials = { login: 'cedric', password: '<PASSWORD>' }; userService.authenticate(credentials) .subscribe(() => { expect(userService.storeLoggedInUser).toHaveBeenCalledWith(user); expect(httpService.post).toHaveBeenCalledWith('/api/users/authentication', credentials); }); })); it('should store the logged in user', () => { spyOn(userService.userEvents, 'next'); spyOn(window.localStorage, 'setItem'); userService.storeLoggedInUser(user); expect(userService.userEvents.next).toHaveBeenCalledWith(user); expect(window.localStorage.setItem).toHaveBeenCalledWith('rememberMe', JSON.stringify(user)); }); it('should retrieve no user if none stored', () => { spyOn(userService.userEvents, 'next'); spyOn(window.localStorage, 'getItem').and.returnValue(JSON.stringify(user)); userService.retrieveUser(); expect(userService.userEvents.next).toHaveBeenCalledWith(user); }); it('should retrieve no user if none stored', () => { spyOn(userService.userEvents, 'next'); spyOn(window.localStorage, 'getItem'); userService.retrieveUser(); expect(userService.userEvents.next).not.toHaveBeenCalled(); }); it('should logout the user', () => { spyOn(userService.userEvents, 'next'); spyOn(window.localStorage, 'removeItem'); userService.logout(); expect(userService.userEvents.next).toHaveBeenCalledWith(null); expect(window.localStorage.removeItem).toHaveBeenCalledWith('rememberMe'); }); });
redboul/ponyracer-ng2
src/app/models/race.model.ts
<reponame>redboul/ponyracer-ng2<gh_stars>0 import { PonyModel } from './pony.model'; export interface RaceModel { id: number; betPonyId?: number; name: string; ponies: Array<PonyModel>; startInstant: string; }
redboul/ponyracer-ng2
src/app/menu/menu.component.ts
<gh_stars>0 import { Component, OnInit, OnDestroy } from '@angular/core'; import { Router } from '@angular/router'; import { Subscription } from 'rxjs/Subscription'; import { UserModel } from '../models/user.model'; import { UserService } from '../user.service'; @Component({ selector: 'pr-menu', templateUrl: './menu.component.html', styleUrls: ['./menu.component.css'] }) export class MenuComponent implements OnInit, OnDestroy { navbarCollapsed = true; user: UserModel; userEventsSubscription: Subscription; constructor(private userService: UserService, private router: Router) { } ngOnInit() { this.userEventsSubscription = this.userService.userEvents.subscribe(user => this.user = user); } ngOnDestroy() { if (this.userEventsSubscription) { this.userEventsSubscription.unsubscribe(); } } toggleNavbar() { this.navbarCollapsed = !this.navbarCollapsed; } logout(event) { event.preventDefault(); this.userService.logout(); this.router.navigate(['/']); } }
redboul/ponyracer-ng2
src/app/ws.service.spec.ts
import { TestBed, async } from '@angular/core/testing'; import { WsService } from './ws.service'; describe('WsService', () => { let wsService: WsService; const webstomp = jasmine.createSpyObj('Webstomp', ['over', 'connect', 'subscribe']); class FakeWebSocket { close() {}} beforeEach(() => { TestBed.configureTestingModule({ providers: [ WsService, { provide: 'WebSocket', useValue: FakeWebSocket }, { provide: 'Webstomp', useValue: webstomp } ] }); }); beforeEach(() => wsService = TestBed.get(WsService)); it('should connect to a websocket channel', async(() => { // given a fake WebSocket connection webstomp.over.and.returnValue(webstomp); webstomp.connect.and.callFake((headers, callback) => callback()); webstomp.subscribe.and.callFake((channel, callback) => { expect(channel).toBe('/channel/2'); callback({ body: '{"id": 1}' }); }); // when connecting to a channel const messages = wsService.connect('/channel/2'); messages.subscribe(message => { expect(message.id).toBe(1); }); // then we should have a WebSocket connection with Stomp protocol expect(webstomp.over).toHaveBeenCalled(); })); it('should throw on error if the connection fails', async(() => { // given a fake WebSocket connection webstomp.over.and.returnValue(webstomp); // when connecting to a channel const messages = wsService.connect('/channel/2'); // with a failed connection webstomp.connect.and.callFake((headers, callback, errorCallback) => errorCallback(new Error('Oops!'))); // then we should have an error in the observable messages.subscribe( message => fail(), error => { expect(error.message).toBe('Oops!'); } ); })); it('should unsubscribe from the websocket connection on unsubscription', async(() => { // given a fake WebSocket connection webstomp.over.and.returnValue(webstomp); // returning a subscription webstomp.connect.and.callFake((headers, callback) => callback()); const fakeSubscription = jasmine.createSpyObj('Subscription', ['unsubscribe']); webstomp.subscribe.and.returnValue(fakeSubscription); // when connecting to a channel const messages = wsService.connect('/channel/2'); // and unsubscribing const subscription = messages.subscribe(() => { }); subscription.unsubscribe(); // then we should have unsubscribe from the Websocket connection expect(fakeSubscription.unsubscribe).toHaveBeenCalled(); })); });
redboul/ponyracer-ng2
src/app/home/home.component.spec.ts
import { TestBed } from '@angular/core/testing'; import { RouterTestingModule } from '@angular/router/testing'; import { BehaviorSubject } from 'rxjs/BehaviorSubject'; import { AppModule } from '../app.module'; import { HomeComponent } from './home.component'; import { UserModel } from '../models/user.model'; import { UserService } from '../user.service'; describe('HomeComponent', () => { const fakeUserService = {userEvents: new BehaviorSubject<UserModel>(undefined)} as UserService; beforeEach(() => TestBed.configureTestingModule({ imports: [AppModule, RouterTestingModule] })); it('display the title and quote', () => { const fixture = TestBed.createComponent(HomeComponent); const element = fixture.nativeElement; const title = element.querySelector('h1'); expect(title).not.toBeNull('You should have an `h1` element to display the title'); expect(title.textContent).toContain('Ponyracer Always a pleasure to bet on ponies'); const subtitle = element.querySelector('small'); expect(subtitle).not.toBeNull('You should have a `small` element to display the subtitle'); expect(subtitle.textContent).toContain('Always a pleasure to bet on ponies'); }); it('display a link to go the login and another to register', () => { const fixture = TestBed.createComponent(HomeComponent); const element = fixture.nativeElement; fixture.detectChanges(); fixture.componentInstance.user = null; fixture.detectChanges(); const button = element.querySelector('a[href="/login"]'); expect(button).not.toBeNull('You should have an `a` element to display the link to the login. Maybe you forgot to use `routerLink`?'); expect(button.textContent).toContain('Login', 'The link should have a text'); const buttonRegister = element.querySelector('a[href="/register"]'); expect(buttonRegister) .not.toBeNull('You should have an `a` element to display the link to the register page. Maybe you forgot to use `routerLink`?'); expect(buttonRegister.textContent).toContain('Register', 'The link should have a text'); }); it('should listen to userEvents in ngOnInit', (done) => { const component = new HomeComponent(fakeUserService); component.ngOnInit(); const user = {login: 'cedric', money: 200} as UserModel; fakeUserService.userEvents.next(user); fakeUserService.userEvents.subscribe(() => { expect(component.user).toBe(user, 'Your component should listen to the `userEvents` observable'); done(); }); }); it('should unsubscribe on destroy', () => { const component = new HomeComponent(fakeUserService); component.ngOnInit(); spyOn(component.userEventsSubscription, 'unsubscribe'); component.ngOnDestroy(); expect(component.userEventsSubscription.unsubscribe).toHaveBeenCalled(); }); it('should display only a link to go the races page if logged in', () => { const fixture = TestBed.createComponent(HomeComponent); fixture.detectChanges(); fixture.componentInstance.user = {login: 'cedric'} as UserModel; fixture.detectChanges(); const element = fixture.nativeElement; const button = element.querySelector('a[href="/races"]'); expect(button).not.toBeNull('The link should lead to the races if the user is logged'); expect(button.textContent).toContain('Races', 'The first link should lead to the races if the user is logged'); }); });
redboul/ponyracer-ng2
e2e/app.e2e-spec.ts
import { PonyracerPage } from './app.po'; describe('ponyracer App', function() { let page: PonyracerPage; beforeEach(() => { page = new PonyracerPage(); }); it('should display message saying app works', () => { page.navigateTo(); expect(page.getParagraphText()).toEqual('Ponyracer Always a pleasure to bet on ponies'); }); });
redboul/ponyracer-ng2
src/app/http.service.ts
import { Injectable } from '@angular/core'; import { Http, RequestOptions, Headers } from '@angular/http'; import { Observable } from 'rxjs/Observable'; import 'rxjs/add/operator/map'; @Injectable() export class HttpService { baseUrl: string = 'http://ponyracer.ninja-squad.com'; headers: Headers = new Headers(); options: RequestOptions = new RequestOptions({ headers: this.headers }); constructor(private http: Http) { } get(path: string): Observable<any> { this.addJwtTokenIfExists(); return this.http.get(`${this.baseUrl}${path}`, this.options) .map(res => res.json()); } post(path: string, body: any): Observable<any> { this.addJwtTokenIfExists(); return this.http.post(`${this.baseUrl}${path}`, body, this.options) .map(res => res.json()); } delete(path: string): Observable<any> { this.addJwtTokenIfExists(); return this.http.delete(`${this.baseUrl}${path}`, this.options); } addJwtTokenIfExists() { const value = window.localStorage.getItem('rememberMe'); if (value) { const user = JSON.parse(value); this.headers.set('Authorization', `Bearer ${user.token}`); } else { this.headers.delete('Authorization'); } } }
redboul/ponyracer-ng2
src/app/menu/menu.component.spec.ts
import { async, TestBed } from '@angular/core/testing'; import { RouterTestingModule } from '@angular/router/testing'; import { Subject } from 'rxjs/Subject'; import { AppModule } from '../app.module'; import { MenuComponent } from './menu.component'; import { UserService } from '../user.service'; import { UserModel } from '../models/user.model'; describe('MenuComponent', () => { const fakeUserService = { userEvents: new Subject<UserModel>(), logout: () => {} } as UserService; const fakeRouter = jasmine.createSpyObj('Router', ['navigate']); beforeEach(() => TestBed.configureTestingModule({ imports: [AppModule, RouterTestingModule], providers: [ { provide: UserService, useValue: fakeUserService } ] })); it('should have a `navbarCollapsed` field', () => { const menu: MenuComponent = new MenuComponent(fakeUserService, fakeRouter); menu.ngOnInit(); expect(menu.navbarCollapsed) .toBe(true, 'Check that `navbarCollapsed` is initialized with `true`.' + 'Maybe you forgot to declare `navbarCollapsed` in your component.'); }); it('should have a `toggleNavbar` method', () => { const menu: MenuComponent = new MenuComponent(fakeUserService, fakeRouter); expect(menu.toggleNavbar) .not.toBeNull('Maybe you forgot to declare a `toggleNavbar()` method'); menu.toggleNavbar(); expect(menu.navbarCollapsed) .toBe(false, '`toggleNavbar()` should change `navbarCollapsed` from true to false`'); menu.toggleNavbar(); expect(menu.navbarCollapsed) .toBe(true, '`toggleNavbar()` should change `navbarCollapsed` from false to true`'); }); it('should toggle the class on click', () => { const fixture = TestBed.createComponent(MenuComponent); const element = fixture.nativeElement; fixture.detectChanges(); const navbarCollapsed = element.querySelector('#navbar'); expect(navbarCollapsed).not.toBeNull('No element with the id `#navbar`'); expect(navbarCollapsed.classList).toContain('collapse', 'The element with the id `#navbar` should have the class `collapse`'); const button = element.querySelector('button'); expect(button).not.toBeNull('No `button` element to collapse the menu'); button.dispatchEvent(new Event('click')); fixture.detectChanges(); const navbar = element.querySelector('#navbar'); expect(navbar.classList).not .toContain('collapse', 'The element with the id `#navbar` should have not the class `collapse` after a click'); }); it('should use routerLink to navigate', () => { const fixture = TestBed.createComponent(MenuComponent); const element = fixture.nativeElement; fixture.detectChanges(); const links = element.querySelectorAll('a[routerLink]'); expect(links.length).toBe(2, 'You should have two routerLink: one to the races, one to the home'); }); it('should listen to userEvents in ngOnInit', async(() => { const component = new MenuComponent(fakeUserService, fakeRouter); component.ngOnInit(); const user = { login: 'cedric', money: 200 } as UserModel; fakeUserService.userEvents.subscribe(() => { expect(component.user).toBe(user, 'Your component should listen to the `userEvents` observable'); }); fakeUserService.userEvents.next(user); })); it('should display the user if logged', () => { const fixture = TestBed.createComponent(MenuComponent); fixture.detectChanges(); const component = fixture.componentInstance; component.user = { login: 'cedric', money: 200 } as UserModel; fixture.detectChanges(); const element = fixture.nativeElement; const info = element.querySelector('a.nav-item.nav-link.float-md-right'); expect(info) .not.toBeNull('You should have an `a` element with the classes `nav-item nav-link float-md-right` to display the user info'); expect(info.textContent).toContain('cedric', 'You should display the user\'s name in a `a` element'); expect(info.textContent).toContain('200', 'You should display the user\'s score in a `a` element'); }); it('should unsubscribe on destroy', () => { const component = new MenuComponent(fakeUserService, fakeRouter); component.ngOnInit(); spyOn(component.userEventsSubscription, 'unsubscribe'); component.ngOnDestroy(); expect(component.userEventsSubscription.unsubscribe).toHaveBeenCalled(); }); it('should display a logout button', () => { const fixture = TestBed.createComponent(MenuComponent); const component = fixture.componentInstance; component.user = { login: 'cedric', money: 200 } as UserModel; fixture.detectChanges(); spyOn(fixture.componentInstance, 'logout'); const element = fixture.nativeElement; const logout = element.querySelector('span.fa-power-off'); expect(logout).not.toBeNull('You should have a span element with a class `fa-power-off` to log out'); logout.dispatchEvent(new Event('click', { bubbles: true })); fixture.detectChanges(); expect(fixture.componentInstance.logout).toHaveBeenCalled(); }); it('should stop the click event propagation', () => { const component = new MenuComponent(fakeUserService, fakeRouter); const event = new Event('click'); spyOn(fakeUserService, 'logout'); spyOn(event, 'preventDefault'); component.logout(event); expect(fakeUserService.logout).toHaveBeenCalled(); expect(event.preventDefault).toHaveBeenCalled(); expect(fakeRouter.navigate).toHaveBeenCalledWith(['/']); }); });
redboul/ponyracer-ng2
src/app/race.service.spec.ts
import { async, TestBed } from '@angular/core/testing'; import { Observable } from 'rxjs/Observable'; import { Subject } from 'rxjs/Subject'; import 'rxjs/add/observable/of'; import { RaceService } from './race.service'; import { HttpService } from './http.service'; import { WsService } from './ws.service'; import { PonyWithPositionModel } from './models/pony.model'; describe('RaceService', () => { let raceService: RaceService; const httpService = jasmine.createSpyObj('HttpService', ['get', 'post', 'delete']); const wsService = jasmine.createSpyObj('WsService', ['connect']); beforeEach(() => TestBed.configureTestingModule({ providers: [ { provide: HttpService, useValue: httpService }, { provide: WsService, useValue: wsService }, RaceService ] })); beforeEach(() => raceService = TestBed.get(RaceService)); it('should return an Observable of 3 races', async(() => { // fake response const hardcodedRaces = [{ name: 'Paris' }, { name: 'Tokyo' }, { name: 'Lyon' }]; httpService.get.and.returnValue(Observable.of(hardcodedRaces)); raceService.list().subscribe(races => { expect(races.length).toBe(3); expect(httpService.get).toHaveBeenCalledWith('/api/races?status=PENDING'); }); })); it('should get a race', async(() => { // fake response const race = { name: 'Paris' }; httpService.get.and.returnValue(Observable.of(race)); const raceId = 1; raceService.get(raceId).subscribe(() => { expect(httpService.get).toHaveBeenCalledWith('/api/races/1'); }); })); it('should bet on a race', async(() => { // fake response httpService.post.and.returnValue(Observable.of({ id: 1 })); const raceId = 1; const ponyId = 2; raceService.bet(raceId, ponyId).subscribe(() => { expect(httpService.post).toHaveBeenCalledWith('/api/races/1/bets', { ponyId }); }); })); it('should cancel a bet on a race', async(() => { // fake response httpService.delete.and.returnValue(Observable.of(null)); const raceId = 1; raceService.cancelBet(raceId).subscribe(() => { expect(httpService.delete).toHaveBeenCalledWith('/api/races/1/bets'); }); })); it('should return live positions from websockets', async(() => { const raceId = 1; const messages = new Subject<{status: string; ponies: Array<PonyWithPositionModel>}>(); let positions: Array<PonyWithPositionModel> = []; wsService.connect.and.returnValue(messages); raceService.live(raceId).subscribe(pos => { positions = pos; }); expect(wsService.connect).toHaveBeenCalledWith(`/race/${raceId}`); messages.next({ status: 'RUNNING', ponies: [{ id: 1, name: '<NAME>', color: 'BLUE', position: 1 }] }); messages.next({ status: 'RUNNING', ponies: [{ id: 1, name: '<NAME>', color: 'BLUE', position: 100 }] }); expect(positions.length).toBe(1); expect(positions[0].position).toBe(100); })); });
redboul/ponyracer-ng2
src/app/ws.service.ts
<filename>src/app/ws.service.ts<gh_stars>0 import { Injectable, Inject } from '@angular/core'; import * as Webstomp from 'webstomp-client'; import { Observable } from 'rxjs/Observable'; @Injectable() export class WsService { constructor(@Inject('Webstomp') private Webstomp, @Inject('WebSocket') private WebSocket) { } connect(channel): Observable<any> { return Observable.create(observer => { const connection = new this.WebSocket('ws://ponyracer.ninja-squad.com/ws'); const stompClient = this.Webstomp.over(connection); let subscription; stompClient.connect({login: null, passcode: null}, () => subscription = stompClient.subscribe(channel, message => observer.next(JSON.parse(message.body))), error => observer.error(error)); return () => { if (subscription) { subscription.unsubscribe(); } connection.close(); }; }); } }
redboul/ponyracer-ng2
src/app/race/race.component.spec.ts
import { TestBed } from '@angular/core/testing'; import { RouterTestingModule } from '@angular/router/testing'; import { By } from '@angular/platform-browser'; import { AppModule } from '../app.module'; import { RaceComponent } from './race.component'; import { PonyComponent } from '../pony/pony.component'; describe('RaceComponent', () => { beforeEach(() => TestBed.configureTestingModule({ imports: [AppModule, RouterTestingModule] })); it('should display a race name and its ponies', () => { const fixture = TestBed.createComponent(RaceComponent); // given a race in Paris with 5 ponies const raceComponent = fixture.componentInstance; raceComponent.raceModel = { id: 12, name: 'Paris', ponies: [ { id: 1, name: 'Gentle Pie', color: 'YELLOW' }, { id: 2, name: 'Big Soda', color: 'ORANGE' }, { id: 3, name: 'Gentle Bottle', color: 'PURPLE' }, { id: 4, name: 'Superb Whiskey', color: 'GREEN' }, { id: 5, name: 'Fast Rainbow', color: 'BLUE' } ], startInstant: '2016-02-18T08:02:00Z' }; // when triggering the change detection fixture.detectChanges(); // then we should have the name and ponies displayed in the template const element = fixture.nativeElement; const raceName = element.querySelector('h2'); expect(raceName).not.toBeNull('You need an h2 element for the race name'); expect(raceName.textContent).toContain('Paris', 'The h2 element should contain the race name'); const directives = fixture.debugElement.queryAll(By.directive(PonyComponent)); expect(directives).not.toBeNull('You should use the PonyComponent in your template to display the ponies'); expect(directives.length).toBe(5, 'You should have five pony components in your template'); const startInstant = element.querySelector('p'); expect(startInstant).not.toBeNull('You should use a `p` element to display the start instant'); expect(startInstant.textContent).toContain('ago', 'You should use the `fromNow` pipe you created to format the start instant'); }); });
redboul/ponyracer-ng2
src/app/bet/bet.component.spec.ts
<filename>src/app/bet/bet.component.spec.ts import { async, TestBed } from '@angular/core/testing'; import { ActivatedRoute } from '@angular/router'; import { RouterTestingModule } from '@angular/router/testing'; import { By } from '@angular/platform-browser'; import { Observable } from 'rxjs/Observable'; import 'rxjs/add/observable/of'; import 'rxjs/add/observable/throw'; import { AppModule } from '../app.module'; import { RaceService } from '../race.service'; import { BetComponent } from './bet.component'; import { PonyComponent } from '../pony/pony.component'; import { RaceModel } from '../models/race.model'; import { PonyModel } from '../models/pony.model'; describe('BetComponent', () => { const fakeRaceService = jasmine.createSpyObj('RaceService', ['get', 'bet', 'cancelBet']); const race = { id: 1, name: 'Paris' }; fakeRaceService.get.and.returnValue(Observable.of(race)); const fakeActivatedRoute = { snapshot: { params: { raceId: 1 } } }; beforeEach(() => TestBed.configureTestingModule({ imports: [AppModule, RouterTestingModule], providers: [ { provide: RaceService, useValue: fakeRaceService }, { provide: ActivatedRoute, useValue: fakeActivatedRoute } ] })); it('should display a race name, its date and its ponies', () => { const fixture = TestBed.createComponent(BetComponent); fixture.detectChanges(); // given a race in Paris with 5 ponies const betComponent = fixture.componentInstance; betComponent.raceModel = { id: 12, name: 'Paris', ponies: [ { id: 1, name: 'Gentle Pie', color: 'YELLOW' }, { id: 2, name: 'Big Soda', color: 'ORANGE' }, { id: 3, name: 'Gentle Bottle', color: 'PURPLE' }, { id: 4, name: 'Superb Whiskey', color: 'GREEN' }, { id: 5, name: 'Fast Rainbow', color: 'BLUE' } ], startInstant: '2016-02-18T08:02:00Z' }; // when triggering the change detection fixture.detectChanges(); // then we should have the name and ponies displayed in the template const directives = fixture.debugElement.queryAll(By.directive(PonyComponent)); expect(directives).not.toBeNull('You should use the PonyComponent in your template to display the ponies'); expect(directives.length).toBe(5, 'You should have five pony components in your template'); const element = fixture.nativeElement; const raceName = element.querySelector('h2'); expect(raceName).not.toBeNull('You need an h2 element for the race name'); expect(raceName.textContent).toContain('Paris', 'The h2 element should contain the race name'); const startInstant = element.querySelector('p'); expect(startInstant).not.toBeNull('You should use a `p` element to display the start instant'); expect(startInstant.textContent).toContain('ago', 'You should use the `fromNow` pipe you created to format the start instant'); }); it('should trigger a bet when a pony is clicked', async(() => { const fixture = TestBed.createComponent(BetComponent); fixture.detectChanges(); fakeRaceService.bet.and.returnValue(Observable.of({ id: 12, name: 'Paris', ponies: [ { id: 1, name: '<NAME>', color: 'YELLOW' }, { id: 2, name: 'Big Soda', color: 'ORANGE' } ], startInstant: '2016-02-18T08:02:00Z', betPonyId: 1 })); // given a race in Paris with 5 ponies const betComponent = fixture.componentInstance; betComponent.raceModel = { id: 12, name: 'Paris', ponies: [ { id: 1, name: '<NAME>', color: 'YELLOW' }, { id: 2, name: '<NAME>', color: 'ORANGE' } ], startInstant: '2016-02-18T08:02:00Z' }; fixture.detectChanges(); // when we emit a `ponyClicked` event const directives = fixture.debugElement.queryAll(By.directive(PonyComponent)); const gentlePie = directives[0].componentInstance; // then we should have placed a bet on the pony gentlePie.ponyClicked.subscribe(() => { expect(fakeRaceService.bet).toHaveBeenCalledWith(12, 1); }); gentlePie.ponyClicked.emit(betComponent.raceModel.ponies[0]); })); it('should test if the pony is the one we bet on', () => { const fixture = TestBed.createComponent(BetComponent); const component = fixture.componentInstance; component.raceModel = { id: 12, name: 'Paris', ponies: [ { id: 1, name: '<NAME>', color: 'YELLOW' }, { id: 2, name: '<NAME>', color: 'ORANGE' } ], startInstant: '2016-02-18T08:02:00Z', betPonyId: 1 }; const pony = { id: 1 }; const isSelected = component.isPonySelected(pony); expect(isSelected).toBe(true, 'The `isPonySelected` medthod should return true if the pony is selected'); }); it('should initialize the race with ngOnInit', () => { const fixture = TestBed.createComponent(BetComponent); const component = fixture.componentInstance; expect(component.raceModel).toBeUndefined(); fakeActivatedRoute.snapshot.params = { raceId: 1 }; component.ngOnInit(); expect(component.raceModel).toBe(race, '`ngOnInit` should initialize the `raceModel`'); expect(fakeRaceService.get).toHaveBeenCalledWith(1); }); it('should display an error message if bet failed', () => { const fixture = TestBed.createComponent(BetComponent); fakeRaceService.bet.and.callFake(() => Observable.throw(new Error('Oops'))); const component = fixture.componentInstance; component.raceModel = { id: 2 } as RaceModel; expect(component.betFailed).toBe(false); const pony = { id: 1 }; component.betOnPony(pony); expect(component.betFailed).toBe(true); fixture.detectChanges(); const element = fixture.nativeElement; const message = element.querySelector('.alert.alert-danger'); expect(message.textContent).toContain('The race is already started or finished'); }); it('should cancel a bet', () => { const fixture = TestBed.createComponent(BetComponent); fakeRaceService.cancelBet.and.returnValue(Observable.of(null)); const component = fixture.componentInstance; component.raceModel = { id: 2, betPonyId: 1, name: 'Lyon', ponies: [], startInstant: '2016-02-18T08:02:00Z' }; const pony = { id: 1 } as PonyModel; component.betOnPony(pony); expect(fakeRaceService.cancelBet).toHaveBeenCalledWith(2); expect(component.raceModel.betPonyId).toBeNull(); }); it('should display a message if canceling a bet fails', () => { const fixture = TestBed.createComponent(BetComponent); fixture.detectChanges(); fakeRaceService.cancelBet.and.callFake(() => Observable.throw(new Error('Oops'))); const component = fixture.componentInstance; component.raceModel = { id: 2, betPonyId: 1, name: 'Lyon', ponies: [], startInstant: '2016-02-18T08:02:00Z' }; expect(component.betFailed).toBe(false); const pony = { id: 1 } as PonyModel; component.betOnPony(pony); expect(fakeRaceService.cancelBet).toHaveBeenCalledWith(2); expect(component.raceModel.betPonyId).toBe(1); expect(component.betFailed).toBe(true); }); it('should display a link to go to live', () => { const fixture = TestBed.createComponent(BetComponent); fixture.detectChanges(); const component = fixture.componentInstance; component.raceModel = { id: 2, betPonyId: 1, name: 'Lyon', ponies: [], startInstant: '2016-02-18T08:02:00Z' }; fixture.detectChanges(); const element = fixture.nativeElement; const button = element.querySelector('a[href="/races/2/live"]'); expect(button).not.toBeNull('You should have a link to go to the live with an href `/races/id/live`'); expect(button.textContent).toContain('Watch live!'); }); });
redboul/ponyracer-ng2
src/app/races/races.component.ts
<filename>src/app/races/races.component.ts import { Component, OnInit } from '@angular/core'; import { RaceModel } from '../models/race.model'; import { RaceService } from '../race.service'; @Component({ selector: 'pr-races', templateUrl: './races.component.html', styleUrls: ['./races.component.css'] }) export class RacesComponent implements OnInit { races: Array<RaceModel> = []; constructor(private raceService: RaceService) {} ngOnInit() { this.raceService.list().subscribe(races => this.races = races); } }
LeeJaeBae/second-nest
src/movies/movies.service.spec.ts
<reponame>LeeJaeBae/second-nest<gh_stars>0 import { Test, TestingModule } from "@nestjs/testing"; import { MoviesService } from "./movies.service"; import { Movie } from "./entities/movie.entity"; import { NotFoundException } from "@nestjs/common"; describe("MoviesService", () => { let service: MoviesService; beforeEach(async () => { const module: TestingModule = await Test.createTestingModule({ providers: [MoviesService] }).compile(); service = module.get<MoviesService>(MoviesService); }); it("should be defined", () => { expect(service).toBeDefined(); }); describe("getAll", () => { it("should return an array", () => { expect(service.getAll()).toBeInstanceOf(Array); }); }); describe("getOne", () => { it("should return a movie", () => { service.create({ title: "TestMovie", year: 2000, genres: ["test"] }); const movie = service.getOne(1); expect(movie).toBeDefined(); expect(movie.id).toEqual(1); }); it("should throw 404 error", () => { try { service.getOne(999); } catch (e) { expect(e).toBeInstanceOf(NotFoundException); expect(e.message).toEqual(`Movie with ID;999 is not found.`); } }); }); describe("deleteOne", () => { it("should delete a movie", () => { service.create({ title: "TestMovie", year: 2000, genres: ["test"] }); const allMovies = service.getAll().length; service.deleteOne(1); const afterDelete = service.getAll().length; expect(afterDelete).toBeLessThan(allMovies); }); it("should throw a NotFoundException", () => { try { service.deleteOne(9999); } catch (e) { expect(e).toBeInstanceOf(NotFoundException); } }); }); describe("createMovie", () => { it("should create a movie", () => { const allMovies = service.getAll().length; service.create({ title: "TestMovie", year: 2000, genres: ["test"] }); const afterCreate = service.getAll().length; expect(afterCreate).toBeGreaterThan(allMovies); }); }); describe("updateMovie", () => { it("should update a movie", () => { service.create({ title: "Test", year: 2000, genres: ["test"] }); service.update(1, { title: "Update Test" }); expect(service.getOne(1).title).toEqual("Update Test"); }); it("should throw a NotFoundException", () => { try { service.deleteOne(9999); } catch (e) { expect(e).toBeInstanceOf(NotFoundException); } }); it("should be sorted", () => { for (let i = 0; i < 3; i++) { service.create({ title: "Test", year: 2000 + i, genres: ["test"] }); } service.update(2, { title: "idTest" }); expect(service.getAll()[1]).toEqual(service.getOne(2)); }); }); });
keyone2693/persian-time-ago-pipe
src/app/persian-time-ago/persian-time-ago.module.ts
<reponame>keyone2693/persian-time-ago-pipe import { NgModule } from '@angular/core'; import { PersianTimeAgoPipe } from './persian-time-ago.pipe'; @NgModule({ declarations: [PersianTimeAgoPipe], exports: [PersianTimeAgoPipe], providers: [PersianTimeAgoPipe] }) export class PersianTimeAgoModule { }
keyone2693/persian-time-ago-pipe
public_api.ts
export * from './src/app/persian-time-ago/persian-time-ago.module'; export * from './src/app/persian-time-ago/persian-time-ago.pipe';
snipem/vscode-run-script
src/extension.ts
<filename>src/extension.ts // run: vsce package import * as vscode from 'vscode'; var fs = require("fs"); export function getCommandFromFile(filename: string, encoding : string) : string | null { let text : string = fs.readFileSync(filename).toString(encoding); let string_to_match : string = "^(#|\/\/|--) run: (.*)$"; var command = null; text.split("\n").forEach((line: string) => { let matched_string : RegExpMatchArray | null = line.match(string_to_match); if(matched_string) { command = matched_string[2]; return; } }); return command; } export function activate(context: vscode.ExtensionContext) { let disposable = vscode.commands.registerCommand('extension.runscript', () => { if (vscode.window.activeTextEditor) { console.debug("Run script: " + vscode.window.activeTextEditor.document.fileName); // TODO Use comment symbol from syntax highlighter // TODO Use encoding of editor var run_command = getCommandFromFile(vscode.window.activeTextEditor.document.fileName, "utf-8"); if (!run_command) { let configuration = vscode.workspace.getConfiguration(); if (configuration.get("runscript.startDebuggingWhenNoRunStatementFound")) { vscode.commands.executeCommand("workbench.action.debug.start"); } return; } var terminal; if (vscode.window.activeTerminal) { terminal = vscode.window.activeTerminal; } else { terminal = vscode.window.createTerminal(); } terminal.sendText(run_command); } }); context.subscriptions.push(disposable); } export function deactivate() {}
snipem/vscode-run-script
src/test/suite/extension.test.ts
<filename>src/test/suite/extension.test.ts import * as assert from 'assert'; // You can import and use all API from the 'vscode' module // as well as import your extension to test it import * as vscode from 'vscode'; import * as runscript from '../../extension'; import * as path from 'path'; suite('Extension Test Suite', () => { vscode.window.showInformationMessage('Start all tests.'); const pathToTestScripts = path.resolve(__dirname, '../../../') + "/test_workspace/"; test('Parse run statement', () => { assert.equal(runscript.getCommandFromFile(pathToTestScripts + "example_test_script.sh", "utf-8"), "./example_test_script.sh && echo done"); assert.equal(runscript.getCommandFromFile(pathToTestScripts + "example_test_script.js", "utf-8"), "uname -a"); }); // test('Run Script in acutal VSCode', () => { // var setting: vscode.Uri = vscode.Uri.parse(pathToTestScripts+"example_unit_test.sh"); // vscode.workspace.openTextDocument(setting).then((a: vscode.TextDocument) => { // vscode.window.showTextDocument(a, 1, false).then(e => { // // e.edit(edit => { // // edit.insert(new vscode.Position(0, 0), "Your advertisement here"); // // }); // vscode.commands.executeCommand('extension.runscript'); // console.log("showing document"); // }); // }, (error: any) => { // console.error(error); // debugger; // }); // }); });
olean-b/express-typescript-stencil-starter
server/app.ts
import * as express from 'express' import * as path from 'path' const app:express.Application = express() app.use(express.static(path.join(__dirname, '../resources'))) app.set('views', path.join(__dirname, '../views')) app.get('/', (_req, res) => { res.sendFile(path.join(__dirname, '../views', 'index.html')) }) app.listen(3000, () => { console.log('listening on port 3000') })
olean-b/express-typescript-stencil-starter
stencil.config.ts
<gh_stars>1-10 import { Config } from '@stencil/core'; import path from 'path' export const config: Config = { namespace: 'expressstencilstarter', outputTargets: [ { type: 'dist', esmLoaderPath: path.join(__dirname, 'resources/components/loader'), dir: path.join(__dirname, 'resources/components'), empty: true, }, { type: 'docs-readme' }, { type: 'www', serviceWorker: null // disable service workers } ] };
olean-b/express-typescript-stencil-starter
src/components/my-component/my-component.tsx
<filename>src/components/my-component/my-component.tsx import { Component, Prop, h } from '@stencil/core'; @Component({ tag: 'my-component', styleUrl: 'my-component.css', shadow: true }) export class MyComponent { /** * The first name */ @Prop() count: string = 'first'; render() { return <div>Your <span class="tomat">{`{ ${this.count} }`}</span> Stencil component!</div>; } }
Mrtinic489/elevator-front
src/client/models/buildSteps/buildStep.ts
export interface BuildStep { id: string; name: string; buildStepScript: Script; } export interface Script { command: string; arguments: string; }
Mrtinic489/elevator-front
src/client/models/projects/grantAccessRequest.ts
export class GrantAccessRequest { projectId: string; userId: string; accessType: string; constructor(projectId: string, userId: string, accessType: string) { this.projectId = projectId; this.userId = userId; this.accessType = accessType; } }
Mrtinic489/elevator-front
src/components/TopBar/index.ts
import { TopBar } from "./TopBar"; export default TopBar
Mrtinic489/elevator-front
src/client/providers/buildProvider.ts
import {BaseProvider} from "./baseProvider"; import {Build} from "../models/build"; export class BuildProvider extends BaseProvider { public getById(projectId: string, buildConfigId: string, id: string) : Promise<Build> { const url = this.apiUrl + '/projects/' + projectId + '/buildConfigs/' + buildConfigId + '/builds/' + id; return this.get<Build>(url); } }
Mrtinic489/elevator-front
src/components/AuthenticationPage/index.ts
<filename>src/components/AuthenticationPage/index.ts<gh_stars>1-10 import {AuthenticationPage} from "./AuthenticationPage" import {withRouter} from "react-router-dom"; export default withRouter(AuthenticationPage)
Mrtinic489/elevator-front
src/components/TopBar/TopBar.tsx
<reponame>Mrtinic489/elevator-front import React from "react"; import styles from './TopBar.module.css' import {ProfileInformation} from "../ProfileInformation/ProfileInformation"; import {User} from "../../client"; interface TopBarProps { goHome: () => void; user?: User } export class TopBar extends React.PureComponent<TopBarProps> { render() { return ( <div className={styles.topbar}> <div className={styles.topbarItem}> <div className={styles.elevatorTitle} onClick={this.props.goHome}> ELEVATOR </div> </div> <div className={styles.topbarItem}> <div className={styles.profileInfo}> <ProfileInformation user={this.props.user}/> </div> </div> </div> ) } }
Mrtinic489/elevator-front
src/components/ProjectPage/index.ts
<reponame>Mrtinic489/elevator-front import { ProjectPage } from "./ProjectPage"; import {withRouter} from "react-router-dom"; export default withRouter(ProjectPage);
Mrtinic489/elevator-front
src/components/NoAuthenticatedUserPage/index.ts
<reponame>Mrtinic489/elevator-front import { withRouter } from "react-router-dom"; import {NoAuthenticatedUserPage} from "./NoAuthenticatedUserPage"; export default withRouter(NoAuthenticatedUserPage)
Mrtinic489/elevator-front
src/client/models/index.ts
<reponame>Mrtinic489/elevator-front export * from './projects' export * from './operationResult' export * from './users' export * from './buildConfigs' export * from './buildSteps' export * from './build'
Mrtinic489/elevator-front
src/client/providers/buildConfigsProvider.ts
<gh_stars>1-10 import {Build, BuildConfig, CreateBuildConfigRequest} from "../models"; import {BaseProvider} from "./baseProvider"; export class BuildConfigsProvider extends BaseProvider { public createBuildConfig(createBuildConfigRequest: CreateBuildConfigRequest): Promise<BuildConfig> { const url = this.apiUrl + '/projects/' + createBuildConfigRequest.projectId + '/buildConfigs'; return this.post<BuildConfig>(url, JSON.stringify(createBuildConfigRequest)); } public getAllBuildConfigs(projectId: string): Promise<BuildConfig[]> { const url = this.apiUrl + '/projects/' + projectId + '/buildConfigs'; return this.get<BuildConfig[]>(url); } public getById(projectId: string, buildConfigId: string): Promise<BuildConfig> { const url = this.apiUrl + '/projects/' + projectId + '/buildConfigs/' + buildConfigId; return this.get<BuildConfig>(url); } public runBuildConfig(projectId: string, buildConfig: BuildConfig): Promise<Build> { const url = this.apiUrl + '/projects/' + projectId + '/buildConfigs/' + buildConfig.id + '/run'; return this.post<Build>(url); } }
Mrtinic489/elevator-front
src/components/CreateProjectModal/CreateProjectModal.tsx
<reponame>Mrtinic489/elevator-front import {RouteComponentProps} from "react-router-dom"; import {ApiClient, CreateProjectRequest} from "../../client"; import React, {ChangeEvent} from "react"; import {Modal} from '@material-ui/core' import styles from './CreateProjectModal.module.css' interface CreateProjectModalProps extends RouteComponentProps { client: ApiClient; } interface CreateProjectModalState { name: string; gitUrl: string; gitToken: string; loading: boolean; } export class CreateProjectModal extends React.PureComponent<CreateProjectModalProps, CreateProjectModalState> { constructor(props: CreateProjectModalProps) { super(props); this.state = {name: '', gitUrl: '', gitToken: '', loading: false}; } handleNameChange = (event: React.ChangeEvent<HTMLInputElement>) => { this.setState({name: event.target.value}); }; handleGitUrlChange = (event: React.ChangeEvent<HTMLInputElement>) => { this.setState({gitUrl: event.target.value}); }; handleGitTokenChange = (event: React.ChangeEvent<HTMLInputElement>) => { this.setState({gitToken: event.target.value}); }; render() { return (<Modal className={styles.modal} open={true} aria-labelledby="simple-modal-title" aria-describedby="simple-modal-description"> <div className={styles.modalContent}> <div className={styles.title}> Add a new project </div> <div className={styles.inputs}> <div className={styles.input}> <div className={styles.inputTitle}> <p>Name</p> </div> <input className={styles.inputValue} onChange={this.handleNameChange} type="text"/> </div><div className={styles.input}> <div className={styles.inputTitle}> <p>Git url</p> </div> <input className={styles.inputValue} onChange={this.handleGitUrlChange} type="text"/> </div><div className={styles.input}> <div className={styles.inputTitle}> <p>Git token</p> </div> <input className={styles.inputValue} onChange={this.handleGitTokenChange} type="text"/> </div> </div> <div className={styles.buttons}> <button className={styles.confirmButton} disabled={this.state.loading} onClick={this.saveProject}>Save</button> <button className={styles.cancelButton} disabled={this.state.loading} onClick={this.cancel}>Cancel</button> </div> </div> </Modal>) } saveProject = () => { const createProjectRequest = new CreateProjectRequest(this.state.name, this.state.gitUrl, this.state.gitToken); this.setState({loading: true}); this.props.client.projects.createProject(createProjectRequest).then(_ => { this.setState({loading: false}); this.props.history.push('/'); } ).catch((error) => { this.setState({loading: false}); console.log(error); this.props.history.push('/'); }) }; cancel = () => { this.props.history.push('/'); } }
Mrtinic489/elevator-front
src/client/providers/buildStepsProvider.ts
<filename>src/client/providers/buildStepsProvider.ts import {BaseProvider} from "./baseProvider"; import {BuildStep, CreateBuildStepRequest, UpdateBuildStepRequest} from "../models/buildSteps"; export class BuildStepsProvider extends BaseProvider { public getAllBuildSteps(projectId: string, buildConfigId: string): Promise<BuildStep[]> { const url = this.apiUrl + '/projects/' + projectId + '/buildConfigs/' + buildConfigId + '/buildSteps'; return this.get<BuildStep[]>(url); } public createBuildStep(projectId: string, createBuildStepRequest: CreateBuildStepRequest): Promise<BuildStep> { const url = this.apiUrl + '/projects/' + projectId + '/buildConfigs/' + createBuildStepRequest.buildConfigId + '/buildSteps'; return this.post<BuildStep>(url, JSON.stringify(createBuildStepRequest)); } public updateBuildStep(projectId: string, buildStepId: string, updateProjectRequest: UpdateBuildStepRequest) { const url = this.apiUrl + '/projects/' + projectId + '/buildConfigs/' + updateProjectRequest.buildConfigId + '/buildSteps/' + buildStepId; return this.put<BuildStep>(url, JSON.stringify(updateProjectRequest)); } }
Mrtinic489/elevator-front
src/client/providers/index.ts
export * from './projectsProvider'; export * from './usersProvider'