type-fest#PartialDeep TypeScript Examples
The following examples show how to use
type-fest#PartialDeep.
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: getVariations.ts From storefront with MIT License | 6 votes |
export default function getVariations(product: PartialDeep<VariableProduct>) {
const varationAttributes =
product.variations?.nodes?.flatMap(
(variation) =>
variation?.attributes?.nodes?.map((attribute) =>
attribute != null
? {
...attribute,
variationId: variation.databaseId,
}
: undefined,
) ?? [],
) ?? [];
return mapValues(groupBy(varationAttributes, 'name'), (attribute) => ({
label: attribute[0]?.label,
name: attribute[0]?.name,
options: uniq(attribute.map((a) => a?.value)).filter(Boolean) as string[],
}));
}
Example #2
Source File: get-ttl.ts From prisma-session-store with MIT License | 6 votes |
getTTL = <M extends string>(
options: Pick<IOptions<M>, 'ttl'>,
session: PartialDeep<SessionData>,
sid: string
) => {
if (typeof options.ttl === 'number') return options.ttl;
if (typeof options.ttl === 'function')
return options.ttl(options, session, sid);
if ((options.ttl as unknown) !== undefined)
throw new TypeError('`options.ttl` must be a number or function.');
const maxAge = session.cookie?.maxAge ?? null;
return typeof maxAge === 'number' ? Math.floor(maxAge) : ONE_DAY_MS;
}
Example #3
Source File: prisma-session-store.ts From prisma-session-store with MIT License | 5 votes |
/**
* Commit the given `session` object associated with the given `sid`.
*
* @param sid the ID to save the session data under
* @param session the session data to save
* @param callback a callback with the results of saving the data
* or an error that occurred
*/
public readonly set = async (
sid: string,
session: PartialDeep<SessionData>,
callback?: (err?: unknown) => void
) => {
if (!(await this.validateConnection())) return callback?.();
const ttl = getTTL(this.options, session, sid);
const expiresAt = createExpiration(ttl, {
rounding: this.options.roundTTL,
});
let sessionString;
try {
sessionString = this.serializer.stringify(session);
} catch (e: unknown) {
this.logger.error(`set(): ${String(e)}`);
if (callback) defer(callback, e);
return;
}
const existingSession = await this.prisma[this.sessionModelName]
.findUnique({
where: { sid },
})
.catch(() => null);
const data = {
sid,
expiresAt,
data: sessionString,
id: this.dbRecordIdIsSessionId ? sid : this.dbRecordIdFunction(sid),
};
try {
if (existingSession !== null) {
await this.prisma[this.sessionModelName].update({
data,
where: { sid },
});
} else {
await this.prisma[this.sessionModelName].create({
data: { ...data, data: sessionString },
});
}
} catch (e: unknown) {
this.logger.error(`set(): ${String(e)}`);
if (callback) defer(callback, e);
return;
}
if (callback) defer(callback);
};
Example #4
Source File: prisma-session-store.ts From prisma-session-store with MIT License | 5 votes |
/**
* Refresh the time-to-live for the session with the given `sid`.
*
* @param sid the id of the session to refresh
* @param session the data of the session to resave
* @param callback a callback notifying that the refresh was completed
* or that an error occurred
*/
public readonly touch = async (
sid: string,
session: PartialDeep<SessionData>,
callback?: (err?: unknown) => void
) => {
if (!(await this.validateConnection())) return callback?.();
const ttl = getTTL(this.options, session, sid);
const expiresAt = createExpiration(ttl, {
rounding: this.options.roundTTL,
});
try {
const existingSession = await this.prisma[
this.sessionModelName
].findUnique({
where: { sid },
});
if (existingSession !== null) {
const existingSessionData = {
...this.serializer.parse(existingSession.data ?? '{}'),
cookie: session.cookie,
};
await this.prisma[this.sessionModelName].update({
where: { sid: existingSession.sid },
data: {
expiresAt,
data: this.serializer.stringify(existingSessionData),
},
});
}
// *** If there is no found session, for some reason, should it be recreated from sess *** ?
if (callback) defer(callback);
} catch (e: unknown) {
this.logger.error(`touch(): ${String(e)}`);
if (callback) defer(callback, e);
}
};
Example #5
Source File: AddToCart.tsx From storefront with MIT License | 4 votes |
AddToCart: React.VFC<Props> = ({ product }) => {
const { addAlert } = useUI();
const [showViewCart, setShowViewCart] = useState(false);
const [variationId, setVariationId] = useState<number>();
const [addToCart, { loading }] = useAddToCartMutation({
refetchQueries: ['Cart'],
awaitRefetchQueries: true,
});
/** Handles adding items to the cart. */
const handleAddToCartClick = async () => {
try {
await addToCart({
variables: {
productId: product.databaseId,
variationId,
},
});
// Show View Cart Button
setShowViewCart(true);
} catch (error) {
if (isApolloError(error)) {
addAlert(error.message, { severity: 'error' });
}
}
};
/** Handles changing the variation. */
const handleVariationChange = (variation?: PartialDeep<ProductVariation>) => {
setVariationId(variation?.databaseId);
};
const viewCart = showViewCart && (
<Button color="secondary" href="/cart">
View cart
</Button>
);
return product.__typename === 'ExternalProduct' ? (
<Button
color="primary"
variant="contained"
href={product.externalUrl ?? '/'}
target="_blank"
rel="noopener noreferrer"
>
Buy now
</Button>
) : product.__typename === 'SimpleProduct' ? (
<>
<Stock product={product} />
<Stack direction="row" spacing={1}>
<Button
color="primary"
variant="contained"
disabled={product.stockStatus === StockStatusEnum.OUT_OF_STOCK}
loading={loading}
onClick={handleAddToCartClick}
>
Add to cart
</Button>
{viewCart}
</Stack>
</>
) : product.__typename === 'VariableProduct' ? (
<>
<VariationForm product={product} onChange={handleVariationChange} />
<Box sx={{ mt: 1 }}>
<Stock
product={product}
variation={product.variations?.nodes?.find(
(variation) => variation?.databaseId === variationId,
)}
/>
</Box>
<Stack direction="row" spacing={1}>
<Button
color="primary"
disabled={!variationId}
loading={loading}
size="large"
variant="contained"
onClick={handleAddToCartClick}
>
Add to cart
</Button>
{viewCart}
</Stack>
</>
) : null;
}
Example #6
Source File: http-client.ts From sdkgen with MIT License | 4 votes |
async makeRequest(ctx: PartialDeep<Context> | null, functionName: string, args: unknown): Promise<any> {
const func = this.astJson.functionTable[functionName];
if (!func) {
throw new Error(`Unknown function ${functionName}`);
}
const extra: Record<string, unknown> = {};
for (const [key, value] of this.extra) {
extra[key] = value;
}
const requestBody = JSON.stringify({
args: encode(this.astJson.typeTable, `${functionName}.args`, func.args, args),
deviceInfo: ctx?.request?.deviceInfo ?? { id: hostname(), type: "node" },
extra: {
...extra,
...ctx?.request?.extra,
},
name: functionName,
requestId: ctx?.request?.id ? ctx.request.id + randomBytes(6).toString("hex") : randomBytes(16).toString("hex"),
version: 3,
});
const options: RequestOptions = {
hostname: this.baseUrl.hostname,
method: "POST",
path: this.baseUrl.pathname,
port: this.baseUrl.port,
headers: {
"content-type": "application/sdkgen",
},
};
const encodedRet = await new Promise<unknown>((resolve, reject) => {
const req = (this.baseUrl.protocol === "http:" ? httpRequest : httpsRequest)(options, res => {
let data = "";
res.on("data", chunk => {
data += chunk;
});
res.on("end", () => {
try {
const response = JSON.parse(data) as object;
if (has(response, "error") && response.error) {
reject(response.error);
} else {
resolve(has(response, "result") ? response.result : null);
}
} catch (error) {
reject({ message: `${error}`, type: "Fatal" });
}
});
res.on("error", error => {
reject({ message: `${error}`, type: "Fatal" });
});
res.on("aborted", () => {
reject({ message: "Request aborted", type: "Fatal" });
});
});
req.on("error", error => {
reject({ message: `${error}`, type: "Fatal" });
});
req.write(requestBody);
req.end();
}).catch(error => {
if (has(error, "type") && has(error, "message") && typeof error.type === "string" && typeof error.message === "string") {
const errClass = this.errClasses[error.type];
if (errClass) {
const errorJson = this.astJson.errors.find(err => (Array.isArray(err) ? err[0] === error.type : err === error.type));
if (errorJson) {
if (Array.isArray(errorJson) && has(error, "data")) {
throw new errClass(error.message, decode(this.astJson.typeTable, `${errClass.name}.data`, errorJson[1], error.data));
} else {
throw new errClass(error.message, undefined);
}
}
}
throw new (this.errClasses.Fatal as new (message: string) => SdkgenError)(`${error.type}: ${error.message}`);
} else {
throw error;
}
});
// eslint-disable-next-line @typescript-eslint/no-unsafe-return
return decode(this.astJson.typeTable, `${functionName}.ret`, func.ret, encodedRet);
}