Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Marcos/edit member infov3 #69

Open
wants to merge 61 commits into
base: main
Choose a base branch
from
Open
Changes from 1 commit
Commits
Show all changes
61 commits
Select commit Hold shift + click to select a range
2e0e2d3
nothing changed
christianjc Dec 4, 2022
ac7be92
Merge branch 'main' of github.com:calblueprint/berkeley-student-coope…
christianjc Feb 8, 2023
4b43807
husky installed
christianjc Feb 8, 2023
7859d93
pulled changes from github
christianjc Feb 27, 2023
545e4a4
fixed packet.json file
christianjc Feb 27, 2023
ffe7d0e
updated package.json
christianjc Feb 27, 2023
e5b8073
setting up Redux and RTK Query. I have set up the redux store and I a…
christianjc Feb 28, 2023
6a1ae94
fixed consoled error, and still wokring on redux and RTK Query
christianjc Mar 1, 2023
a324a8c
set up main apiSlice and shiftsApiSlice
christianjc Mar 1, 2023
00b3949
mereged changes from christian's branch to dev/redux with the basic r…
christianjc Mar 1, 2023
2da2fb2
Set basic redux set up as well as the main apiSlide and the shift co…
christianjc Mar 1, 2023
6eea657
Merge branch 'christian/redux' into dev/redux
christianjc Mar 1, 2023
b7a3bcd
fixed the filtering for unassigned users
christianjc Mar 1, 2023
9c35cf9
woring on unassign and created usersApiSlices
christianjc Mar 1, 2023
91de215
added redux api for users
christianjc Mar 2, 2023
7bd6216
Merge branch 'christian/redux' into dev/redux
christianjc Mar 2, 2023
b0945fe
added some notes
gregoriiaaa Mar 2, 2023
dfeb1a1
merged dev/redux into dev/main and resolved conflicts
gregoriiaaa Mar 2, 2023
19c0aa5
fixing apiSlice errors
gregoriiaaa Mar 4, 2023
50bf0eb
hold up
gregoriiaaa Mar 4, 2023
b464713
npm i
gregoriiaaa Mar 6, 2023
d9c52d8
merged main onto branch
gregoriiaaa Mar 6, 2023
2f31cb4
pull from github
christianjc Mar 6, 2023
4bedefa
setting up testing component for redux
christianjc Mar 6, 2023
eb0e6ae
getshift is working
christianjc Mar 6, 2023
6689e09
updated testing readux file
christianjc Mar 6, 2023
f9e75e9
Merge branch 'main' of github.com:calblueprint/berkeley-student-coope…
gregoriiaaa Mar 6, 2023
8a24672
Merge branch 'greg/fixing-api-bugs' into dev/redux-update
christianjc Mar 6, 2023
62df4ae
Merge branch 'dev/redux-update' into dev/redux
christianjc Mar 6, 2023
d940885
added packages and added CustomFormikFields file
christianjc Mar 6, 2023
6d34f42
updating schema
gregoriiaaa Mar 6, 2023
51fba24
added skeleton of the ScheduledShift type
gregoriiaaa Mar 6, 2023
611d92c
fixing shift form
christianjc Mar 6, 2023
930b3da
updating ShiftForm file
christianjc Mar 6, 2023
b3199d3
Merge branch 'dev/updating-types' into dev/forms
christianjc Mar 6, 2023
11896e2
added functionality to add new shift, not fully tested
christianjc Mar 6, 2023
a8221d1
Merge branch 'dev/forms' into dev/redux-update
christianjc Mar 6, 2023
eabd1db
getShifts and addNewShift works
christianjc Mar 6, 2023
9aabee7
implemented providesTags which allows componets to update when data c…
christianjc Mar 6, 2023
93dd843
made some small changes
christianjc Mar 7, 2023
6894521
Merge branch 'dev/redux-update' into dev/forms
christianjc Mar 7, 2023
d0011f4
editin shifts update
christianjc Mar 7, 2023
f9ab769
Merge branch 'dev/forms' into dev/redux-update
christianjc Mar 7, 2023
1a80855
Fixed the selectShiftById
christianjc Mar 8, 2023
682fc07
will change formik fields
christianjc Mar 8, 2023
635e87b
Merge branch 'dev/redux-apiSlice' into dev/forms
christianjc Mar 8, 2023
44310b5
fixed ShiftForm and formik filds
christianjc Mar 9, 2023
6120855
fixed Post bug
christianjc Mar 9, 2023
45a93d3
Merge branch 'dev/redux-apiSlice' into dev/forms
christianjc Mar 9, 2023
6866ca0
updated shiftForm
christianjc Mar 9, 2023
d3aeead
Merge branch 'dev/forms' of github.com:calblueprint/berkeley-student-…
gregoriiaaa Mar 9, 2023
a7422a7
updated userApi
christianjc Mar 9, 2023
c8bd4a1
fixed user Api
christianjc Mar 9, 2023
841d21a
updated the forms for users
christianjc Mar 9, 2023
b51f1ad
added userForm and editUserCard
christianjc Mar 9, 2023
3ef7b29
added house api slice with fetch, update, and add queries
danashimessele Mar 9, 2023
aa58c36
Merge branch 'dev/reduxHosueApi' of github.com:calblueprint/berkeley-…
gregoriiaaa Mar 11, 2023
43f5588
fixed getHousesQuery
danashimessele Mar 11, 2023
e31a249
greg stuff
gregoriiaaa Mar 11, 2023
4dffcc7
Merge branch 'Danashi/HouseUpdates' of github.com:calblueprint/berkel…
gregoriiaaa Mar 11, 2023
c1b65bf
[feat] Edit User Card in Planner created to edit only the user's name…
Mar 11, 2023
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Prev Previous commit
Next Next commit
hold up
gregoriiaaa committed Mar 4, 2023

Verified

This commit was created on GitHub.com and signed with GitHub’s verified signature. The key has expired.
commit 50bf0ebdcd3e7386a206768f8d6ac670550ef145
355 changes: 253 additions & 102 deletions src/store/api/apiSlice.ts
Original file line number Diff line number Diff line change
@@ -1,105 +1,256 @@
import { createSelector, createEntityAdapter } from '@reduxjs/toolkit'
import { Shift } from '../../types/schema'
import { apiSlice } from '../api/apiSlice'
import { RootState } from '../store'
import { formatMilitaryTime } from '../../utils/utils'

type result = { data: Shift; id: string }
type transformResponse = { data: result[] }

const shiftsAdapter = createEntityAdapter<Shift>({})

const initialState = shiftsAdapter.getInitialState()

export const shiftsApiSlice = apiSlice.injectEndpoints({
endpoints: (builder) => ({
getShifts: builder.query({
query: (houseId) => ({
url: `houses/${houseId}/shifts`,
method: 'GET',
validateStatus: (response, result) => {
// console.log('response: ', response, ' -- result: ', result)
return response.status === 200 && !result.isError
},
}),
// keepUnusedDataFor: 60,
transformResponse: (responseData: transformResponse) => {
// console.log('[transformResponse] responseData: ', responseData)
const loaddedShifts = responseData?.data.map((entity) => {
entity.data.id = entity.id
if (!entity.data.timeWindowDisplay) {
entity.data.timeWindowDisplay =
formatMilitaryTime(entity.data.timeWindow[0]) +
' - ' +
formatMilitaryTime(entity.data.timeWindow[1])
import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react'
import { firestore } from '../../firebase/clientApp'
import {
collection,
doc,
getDocs,
getDoc,
addDoc,
updateDoc,
QuerySnapshot,
DocumentSnapshot,
} from 'firebase/firestore'
import { streamToObject } from '../../utils/utils'

// export type BaseQueryFn<
// Args = any,
// Result = unknown,
// Error = unknown,
// DefinitionExtraOptions = object,
// Meta = object
// > = (
// args: Args,
// api: BaseQueryApi,
// extraOptions: DefinitionExtraOptions
// ) => MaybePromise<QueryReturnValue<Result, Error, Meta>>

// export interface BaseQueryApi {
// signal: AbortSignal
// abort: (reason?: string) => void
// dispatch: ThunkDispatch<any, any, any>
// getState: () => unknown
// extra: unknown
// endpoint: string
// type: 'query' | 'mutation'
// forced?: boolean
// }

// export type QueryReturnValue<T = unknown, E = unknown, M = unknown> =
// | {
// error: E
// data?: undefined
// meta?: M
// }
// | {
// error?: undefined
// data: T
// meta?: M
// }

// type MyResponse =
// | Response
// | { data: Response; error?: undefined }
// | { error: unknown; data?: undefined }
// | null
// | undefined
const baseQuery = fetchBaseQuery({
baseUrl: 'fakeUrl',
fetchFn: async (input: Response) => {
//input: RequestInfo, init: RequestInit | undefined) => {
// console.log('INPUT: ', input)
// console.log('INIT: ', init)
// console.log('ARGS: ', api)
// const resErr: MyResponse = { error: {} }
// const resOk: MyResponse = { data: new Response() }

const resObj: { data: unknown; id: string }[] = []
const okStatus = {
status: 200,
headers: { 'Content-Type': 'application/json' },
}
const errStatus = {
status: 400,
headers: { 'Content-Type': 'application/json' },
}

const { method, url, body } = input

const pathArray = url
.split('fakeUrl')[1]
.split('/')
.filter((p: string) => p.length > 0)

let isCollection = false
// console.log(pathArray)
if (pathArray.length === 0) {
return new Response(
JSON.stringify({
error: { message: 'No path to database entered', isError: true },
}),
errStatus
)
}

let path = ''
pathArray.forEach((p: string, index: number) => {
if (pathArray.length === index + 1) {
path += p
} else {
path += p + '/'
}
})

console.log(path)
if (pathArray.length % 2 !== 0) {
isCollection = true
}

try {
switch (method) {
case 'GET':
//** Check weather the request is a collection or a document */
if (isCollection) {
//** If the query is a collection, get the full collection from the firebase */
const query = collection(firestore, path)
const querySnapshot: QuerySnapshot<unknown> = await getDocs(query)

// console.log('Collection SnapShot.docs: ', querySnapshot.docs)
//** Verify that the object exist */
if (querySnapshot.empty) {
return new Response(
JSON.stringify({
error: { message: 'collection is Empty', isError: true },
}),
errStatus
)
}

//** extract the data from the snapshot object and put it into a new array */
querySnapshot.forEach((doc) => {
// doc.data() is never undefined for query doc snapshots
const data = doc.data()
// console.log(data)
resObj.push({ data: data, id: doc.id.toString() })
// console.log(doc.id, ' => ', doc.data())
})

// console.log(resObj)
return new Response(JSON.stringify({ data: resObj }), okStatus)
} else {
//** If the query is a document, get the document from firebase */
const snapshot: DocumentSnapshot<unknown> = await getDoc(
doc(firestore, path)
)

//** Check if the document exist */
if (!snapshot.exists()) {
return new Response(
JSON.stringify({
error: { message: 'Document does not exist', isError: true },
}),
errStatus
)
}

//** Add resObj to resObj array */
resObj.push({
data: snapshot.data(),
id: pathArray[pathArray.length - 1],
})

// console.log(resObj)
//** Return the resObj wrapped in a Response object */
return new Response(JSON.stringify({ data: resObj }), okStatus)
}

case 'POST':
//** Verify that the path is a collection */
if (!isCollection) {
return new Response(
JSON.stringify({
error: { message: 'Path must be a collection', isError: true },
}),
errStatus
)
}

//** Verify that the body is not empty */
if (!body) {
return new Response(
JSON.stringify({
error: { message: 'Body must not be empty', isError: true },
}),
errStatus
)
}

const postData = await streamToObject(body)

//** Create a new document with the given BODY */
const newDoc = await addDoc(collection(firestore, path), postData)

//** Add resObj to the resObj array */
resObj.push({ data: newDoc, id: newDoc.id.toString() })

//** Return the resObj wrapped in a Response object */
return new Response(JSON.stringify({ data: resObj }), okStatus)

case 'PATCH':
//** Verify that the path is a document */
if (isCollection) {
return new Response(
JSON.stringify({
error: { message: 'Path must be a Document', isError: true },
}),
errStatus
)
}
return entity.data
})
console.debug(loaddedShifts)
return shiftsAdapter.setAll(initialState, loaddedShifts)
},
providesTags: (result, error, arg) => {
if (result?.ids) {
return [
{ type: 'Shift', id: 'LIST' },
...result.ids.map((id) => ({ type: 'Shift', id })),
]
} else return [{ type: 'Shift', id: 'LIST' }]
},
}),
addNewShift: builder.mutation({
query: (data) => ({
url: `houses/${data.houseId}/shifts`,
method: 'POST',
body: {
...data.data,
},
}),
invalidatesTags: [{ type: 'Shift', id: 'LIST' }],
}),
updateShift: builder.mutation({
query: (data) => ({
url: `houses/${data.houseId}/shifts/${data.shiftId}`,
method: 'PATCH',
body: {
...data.data,
},
}),
invalidatesTags: (result, error, arg) => [{ type: 'Shift', id: arg.id }],
}),
// deleteShift: builder.mutation({
// query: ({ id }) => ({
// url: '/shifts',
// method: 'DELETE',
// body: { id },
// }),
// invalidatesTags: (result, error, arg) => [{ type: 'Shift', id: arg.id }],
// }),
}),

//** Verify that the body is not empty */
if (!body) {
return new Response(
JSON.stringify({
error: { message: 'Body must not be empty', isError: true },
}),
errStatus
)
}

const patchData = await streamToObject(body)

//** Patch document with new data */
const updatedDoc = await updateDoc(doc(firestore, path), patchData)

//** Add resObj to the resObj array and return it */
return new Response(
JSON.stringify({
message: `New Document created with id: ${updatedDoc}`,
})
)

case 'DELETE':
break
default:
return null
}
} catch (error) {
console.log(error)
return { error }
}
},
})

export const apiSlice = createApi({
baseQuery,
tagTypes: ['Shift', 'User'],
endpoints: () => ({}),
})

export const {
useGetShiftsQuery,
useAddNewShiftMutation,
useUpdateShiftMutation,
// useDeleteShiftMutation,
} = shiftsApiSlice

// returns the query result object
export const selectShiftsResult = shiftsApiSlice.endpoints.getShifts.select({})

// creates memoized selector
const selectShiftsData = createSelector(
selectShiftsResult,
(shiftsResult) => shiftsResult.data // normalized state object with ids & entries
)

// getSelectors creates these selector and we rename them with aliases using destructing
export const {
selectAll: selectAllShifts,
selectById: selectShiftById,
selectIds: selectShiftIds,
// Pass in a selector that return the shift slice of a state
} = shiftsAdapter.getSelectors(
(state: RootState) => selectShiftsData(state) ?? initialState
)
// export const { useGetHousesQuery } = apiSlice

// getHouses: builder.query({
// query: (path) => ({
// url: `${path}`,
// method: 'GET',
// }),
// }),