Skip to content

Commit

Permalink
vn(feat) wrap: and reminder: rubberduck, dont walk in circles, take a…
Browse files Browse the repository at this point in the history
… step back, be kind to yourself, people are doing their jobs everyday and you're looking to do something like this for months now
  • Loading branch information
varsnothing committed Jan 19, 2024
1 parent ae963d3 commit 8f57cc5
Show file tree
Hide file tree
Showing 18 changed files with 261 additions and 189 deletions.
96 changes: 25 additions & 71 deletions lib/actions/auth-actions.tsx
Original file line number Diff line number Diff line change
@@ -1,68 +1,27 @@
/* eslint-disable react-hooks/exhaustive-deps, react-hooks/rules-of-hooks */
// auth-actions.ts
"use client";
import type { Context } from "react";
import type { IAuthContext, IRMContext, INCharacter } from "@types";
import type {
ISupportedContexts,
IActionBack,
IAction,
IStatus,
ICreateAction,
IDispatch,
IPayload,
} from "@types";

import { useState, useEffect, useContext, useRef } from "react";
import { AuthContext, RMContext, LogContext } from "@state";

/* to-do: chained actions */
// import { decorateRMCharacters } from "@model"

type ActionT = "login" | "logout" | "hydrate" | "update_db";
type ActionTypes = "auth" | "rickmorty";
type ActionAuthNames =
| "load user"
| "unload user"
| "load characters"
| "unload characters"
| "decorate characters"
| "add char to favorites";

type ISupportedContexts = IAuthContext | IRMContext;

interface IActionBack {
action?: ActionT;
type?: ActionTypes;
verb?: ActionAuthNames;
context: Context<ISupportedContexts>;
}

interface IAction {
cb?: Array<() => void>;
}

interface IStatus {
str: string;
ok: boolean | undefined;
current: string;
}

interface IALoginPayload {
name?: string;
avatar?: string;
authd?: boolean;
setter?: () => void;
}

interface ICharacterPayload {
characters?: INCharacter[];
setter?: () => void;
}

type ICreateAction = (
options: IActionBack,
) => (
_options: IAction,
) => [boolean | undefined, (clientPayload?: IAPayload) => void];

type IAPayload = IALoginPayload | ICharacterPayload | Record<any, unknown>;

const CreateAction: ICreateAction =
({ action, type, verb, context }: IActionBack) =>
({ cb }: IAction) => {
const noop = () => {}
console.log({ cb })
// eslint-disable-next-line @typescript-eslint/no-unused-vars
const noop: IDispatch = async (...payload: IPayload): Promise<void> => {};
const createStatusStr = () => {
return `%c Flux: --- action / ${type} / ${action} / ${verb} / ${s_current.current}|${message.current} ---`;
};
Expand All @@ -74,13 +33,13 @@ const CreateAction: ICreateAction =
const init = useRef(false);
const s_current = useRef("loaded");
const message = useRef("");
const to_call = useRef(noop);
const to_call = useRef<IDispatch>(noop);
const status = useRef<IStatus>({
current: s_current.current,
str: createStatusStr(),
ok: undefined,
});
const payload = useRef<IAPayload>();
const payload = useRef<IPayload>();
const [dispatchd, setDispatchd] = useState(false);

const updateStatus = (
Expand All @@ -102,11 +61,11 @@ const CreateAction: ICreateAction =
return;
};

const dispatch = (clientPayload?: IAPayload, toCall) => {
const dispatch: IDispatch = (clientPayload, toCall) => {
payload.current = { ...clientPayload };
s_current.current = "init:active";
message.current = "dispatched";
to_call.current = toCall;
to_call.current = toCall || noop;
updateStatus();
setDispatchd(!dispatchd);
};
Expand Down Expand Up @@ -137,7 +96,7 @@ const CreateAction: ICreateAction =
setter({
..._context,
...payload.current,
history: [..._context.history, status.current.str]
history: [..._context.history, status.current.str],
});
}

Expand All @@ -147,23 +106,18 @@ const CreateAction: ICreateAction =
message.current = "calling functions";
updateStatus({ ok: undefined });

console.log("check to call", { to_call })

if(typeof to_call?.current === 'function') to_call.current(payload.current)
if (typeof to_call?.current === "function")
to_call.current(payload.current);

s_current.current = "completed";
message.current = "success";
updateStatus({ ok: true });


console.log("check cb", { cb })
if (cb?.length > 0) {
console.log("going to run cbs")
cb.forEach((_cb) => {
console.log(" running cb ")
_cb()
});
}

if (cb && cb?.length > 0) {
cb.forEach((_cb) => {
_cb();
});
}

reset();

Expand Down
6 changes: 2 additions & 4 deletions lib/model/decorators/rm-decorator.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,8 +10,8 @@ const decorateCharacter = (
): IDCharacter => {
const decd: IDCharacter = { ...character };
decd.favorite = undefined;
console.log({ favs: uMeta?.rickmorty?.favorites?.characters, id: character.id, match: uMeta?.rickmorty?.favorites?.characters?.includes(character?.id)})
if (uMeta?.rickmorty?.favorites?.characters?.includes(character?.id)) decd.favorite = true;
if (uMeta?.rickmorty?.favorites?.characters?.includes(character?.id))
decd.favorite = true;
else decd.favorite = false;
return decd;
};
Expand All @@ -25,7 +25,5 @@ export const decorateRMCharacters = async (
const decd: IDCharacter[] = characters.map((char) =>
decorateCharacter(char, uMeta),
);

console.log({afterDecd: decd})
return decd;
};
3 changes: 1 addition & 2 deletions lib/model/interfaces/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,8 +8,7 @@ export { getUserMeta } from "./mdb-get-interface";
// write
export { addToFavorites } from "./mdb-update-interface";


/* rm */

// read
export { getRMCharacters } from "./services/rickmorty/rm-connector";
export { getRMCharacters } from "./services/rickmorty/rm-connector";
6 changes: 4 additions & 2 deletions lib/model/interfaces/mdb-get-interface.ts
Original file line number Diff line number Diff line change
Expand Up @@ -73,7 +73,9 @@ const defineSchema =
{ $set: schema },
{ upsert: true },
);
console.log("----- success! ------", { result: JSON.stringify(result) });
console.log("----- db op success! ------", {
result: JSON.stringify(result),
});
};

const defineUserSchema = defineSchema({
Expand All @@ -91,7 +93,7 @@ const initSchemas = async () => {

/* public */
export const getUserMeta = async ({
email = "varsnothing@gmail.com",
email = "",
}: Pick<UserSchema, "email">) => {
const collection = await getUserCollection();
const user = await collection.findOne({ email });
Expand Down
18 changes: 12 additions & 6 deletions lib/model/interfaces/mdb-update-interface.ts
Original file line number Diff line number Diff line change
Expand Up @@ -65,13 +65,19 @@ const getUserCollection = async () => {

/* public */
export const addToFavorites = async ({
email = "varsnothing@gmail.com",
email = "",
cid = undefined,
type = "characters"
}: { email: UserSchema["email"], cid: number }) => {
type = "characters",
}: {
email: UserSchema["email"];
cid: number;
type?: string;
}) => {
const collection = await getUserCollection();
const query = `rickmorty.favorites.${type}`
console.log({ query, email })
const user = await collection.updateOne({ email }, {$addToSet: { [query]: cid }});
const query = `rickmorty.favorites.${type}`;
const user = await collection.updateOne(
{ email },
{ $addToSet: { [query]: cid } },
);
return user;
};
2 changes: 1 addition & 1 deletion lib/state/context-auth.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,5 +7,5 @@ export const AuthContext = createContext<IAuthContext>({
authd: false,
name: "",
setter: undefined,
history: []
history: [],
});
5 changes: 3 additions & 2 deletions lib/state/context-rm.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,9 +7,10 @@ export const RMContext = createContext<IRMContext>({
initd: false,
characters: [],
setter: undefined,
history: []
history: [],
});

export const LogContext = createContext<History>({
history: []
history: [],
setter: undefined,
});
65 changes: 65 additions & 0 deletions lib/types/actions.d.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
// actions.d.ts
import type { Context } from "react";
export type ActionT = "login" | "logout" | "hydrate" | "update_db";
export type ActionTypes = "auth" | "rickmorty";
export type ActionAuthNames =
| "load user"
| "unload user"
| "load characters"
| "unload characters"
| "decorate characters"
| "add char to favorites";

export type ISupportedContexts = IAuthContext | IRMContext | ILogContext;

export interface IActionBack {
action?: ActionT;
type?: ActionTypes;
verb?: ActionAuthNames;
context: Context<ISupportedContexts>;
}

export interface IAction {
cb?: Array<() => void>;
}

export interface IStatus {
str: string;
ok: boolean | undefined;
current: string;
}

export interface IALoginPayload {
name?: string;
avatar?: string;
authd?: boolean;
setter?: () => void;
email?: string;
}

export interface IDAddToFavPayload {
email: string;
cid: number;
}

export interface IACharacterPayload {
characters?: INCharacter[];
setter?: () => void;
cid?: number;
}

export type ICreateAction = (
options: IActionBack,
) => (_options: IAction) => [boolean | undefined, IDispatch];

export type IAPayload = IALoginPayload | IACharacterPayload;
export type IDPayload = IDAddToFavPayload;
export type _IPayload = IAPayload | IDPayload;
export interface IDispatchPayload {
payload?: IAPayload | IDPayload;
func?: IDispatch;
}

export type IPayload = [IDispatchPayload[], IDispatch];

export type IDispatch = (...payload: IPayloadF) => void | Promise<void>;
9 changes: 5 additions & 4 deletions lib/types/contexts.d.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,9 @@
// contexts.d.ts
import type { Dispatch, SetStateAction } from "react";

interface History {
history: string[]
export interface History {
history: string[];
setter: Dispatch<SetStateAction<IAuthContext>> | undefined;
}

export interface INCharacter {
Expand All @@ -16,6 +17,7 @@ export interface INCharacter {
location: {
name: string;
};
favorite?: boolean;
}

export interface IDCharacter extends INCharacter {
Expand All @@ -25,13 +27,12 @@ export interface IDCharacter extends INCharacter {
export interface IAuthContext extends History {
authd?: boolean;
name?: string;
setter: Dispatch<SetStateAction<IAuthContext>> | undefined;
initd?: boolean;
email?: string;
}

// to-do: characters type annotations
export interface IRMContext extends History {
characters?: INCharacter[];
setter: Dispatch<SetStateAction<IAuthContext>> | undefined;
initd?: boolean;
}
22 changes: 21 additions & 1 deletion lib/types/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,28 @@ export type {
IRMContext,
INCharacter,
IDCharacter,
History
History,
} from "./contexts";

// model
export type { UserSchema, User, UserDecoration } from "./model";

// actions
export type {
ActionT,
ActionTypes,
ActionAuthNames,
ISupportedContexts,
IActionBack,
IAction,
IStatus,
IALoginPayload,
IDAddToFavPayload,
IACharacterPayload,
ICreateAction,
IAPayload,
IDPayload,
IPayload,
IDispatch,
IDispatchPayload,
} from "./actions";
Loading

0 comments on commit 8f57cc5

Please sign in to comment.