repo_name
stringlengths
5
122
path
stringlengths
3
232
text
stringlengths
6
1.05M
JakeStanger/Reactive-Gallery
src/pages/gallery/controls/IControlsProps.ts
<gh_stars>0 interface IControlsProps { showLocation: boolean; onChangeShowLocation: (show: boolean) => void; showTime: boolean; onChangeShowTime: (show: boolean) => void; showTags: boolean; onChangeShowTags: (show: boolean) => void; showDescription: boolean; onChangeShowDescription: (show: boolean) => void; query: string; onQueryChange: (query: string) => void; group: string; onGroupChange: (group: string) => void; } export default IControlsProps;
JakeStanger/Reactive-Gallery
server/routes/webhook/Webhook.ts
<gh_stars>0 import { Request, Response } from "express"; import BasketItem from "../../database/models/BasketItem"; import StripeManager from "../../StripeManager"; export const handleStripeWebhook = async (req: Request, res: Response) => { const sig = req.headers["stripe-signature"]; if (!sig) { return res .status(401) .json({ msg: "Webhook can only be triggered by Stripe" }); } let event; try { event = StripeManager.getStripe().webhooks.constructEvent( req.body, sig, process.env.STRIPE_WEBHOOK_SECRET ); } catch (err) { return res.status(400).send(`Webhook Error: ${err.message}`); } // Handle the checkout.session.completed event if (event.type === "checkout.session.completed") { const session = event.data.object as any; // Typings look to be broken? // Clear basket and log await BasketItem.destroy({ where: { user_id: session.client_reference_id } }); } // Return a response to acknowledge receipt of the event res.json({ received: true }); };
JakeStanger/Reactive-Gallery
src/services/basketService/BasketService.ts
<reponame>JakeStanger/Reactive-Gallery import UserService from "../userService/UserService"; import IImage from "../imageService/IImage"; import IBasketItem from "./IBasketItem"; import IPrice from "../priceService/IPrice"; class BasketService { private static _instance: BasketService; private _userService: UserService; private constructor() { this._userService = UserService.getInstance(); } public static getInstance(): BasketService { if (BasketService._instance) return BasketService._instance; else { const instance = new BasketService(); BasketService._instance = instance; return instance; } } public async getBasket(): Promise<IBasketItem[] | {msg: string}> { const res = await fetch("/api/basket", { headers: { Authorization: `Bearer ${this._userService.getToken()}`, } }); if (res.ok && res.status >= 200 && res.status < 300) return res.json(); else return { msg: await res.text() }; } public async addToBasket( image: IImage, price: IPrice, quantity: number, framed: boolean ) { const res = await fetch("/api/basket", { method: "POST", body: JSON.stringify({ image, price, quantity, framed }), headers: { Authorization: `Bearer ${this._userService.getToken()}`, "Content-Type": "application/json" } }); if (res.ok && res.status >= 200 && res.status < 300) return res.json(); else return { msg: await res.text() }; } public async removeFromBasket(basketItem: IBasketItem) { const res = await fetch(`/api/basket/${basketItem.id}`, { method: "DELETE", headers: { Authorization: `Bearer ${this._userService.getToken()}` } }); if (res.ok && res.status >= 200 && res.status < 300) return res.json(); else return { msg: await res.text() }; } public async emptyBasket() { const res = await fetch('/api/basket', { method: 'DELETE', headers: { Authorization: `Bearer ${this._userService.getToken()}` } }); if (res.ok && res.status >= 200 && res.status < 300) return res.json(); else return { msg: await res.text() }; } } export default BasketService;
JakeStanger/Reactive-Gallery
server/database/models/Image.ts
import { Model, DataTypes } from "sequelize"; import Database from "../index"; import Location from "./Location"; import Tag from "./Tag"; import { BelongsToSetAssociationMixin, BelongsToManySetAssociationsMixin } from "sequelize"; import PriceGroup from "./PriceGroup"; import Category from './Category'; class Image extends Model { public id: number; public name: string; public description: string; public filename: string; public width: number; public height: number; public exposure: number; public focalLength: number; public aperture: number; public iso: number; public cameraModel: string; public timeTaken: Date; public deleted: boolean; public setLocation!: BelongsToSetAssociationMixin<Location, "location">; public setTags!: BelongsToManySetAssociationsMixin<Tag, "tags">; public setCategories!: BelongsToManySetAssociationsMixin<Category, "categories">; public setPriceGroup: BelongsToSetAssociationMixin<PriceGroup, "priceGroup">; public readonly categories?: Category[]; public readonly location?: Location; public readonly tags?: Tag[]; public readonly priceGroup: PriceGroup; public static load() { Image.init( { id: { type: DataTypes.INTEGER.UNSIGNED, autoIncrement: true, primaryKey: true }, name: { type: DataTypes.TEXT, allowNull: false }, description: { type: DataTypes.TEXT }, filename: { type: DataTypes.STRING(128) }, width: { type: DataTypes.INTEGER }, height: { type: DataTypes.INTEGER }, exposure: { type: DataTypes.FLOAT }, focalLength: { type: DataTypes.INTEGER }, aperture: { type: DataTypes.INTEGER }, iso: { type: DataTypes.INTEGER }, cameraModel: { type: DataTypes.STRING(32) }, timeTaken: { type: DataTypes.DATE, field: "taken_time" }, deleted: { type: DataTypes.BOOLEAN } }, { sequelize: Database.getConnection(), tableName: "images" } ); } } export default Image;
JakeStanger/Reactive-Gallery
server/database/models/Price.ts
<filename>server/database/models/Price.ts import { Model, DataTypes } from "sequelize"; import Database from "../index"; class Price extends Model { public id: number; public name: string; public unframed: number; public framed: number; public postage: number; public price_group_id: number; public static load() { Price.init( { id: { type: DataTypes.INTEGER.UNSIGNED, autoIncrement: true, primaryKey: true }, name: { type: DataTypes.STRING(255), allowNull: false, unique: true }, unframed: { type: DataTypes.FLOAT }, framed: { type: DataTypes.FLOAT, }, postage: { type: DataTypes.FLOAT } }, { sequelize: Database.getConnection(), tableName: "price" } ); } public static async getFromObject(group: any): Promise<Price> { return await Price.findOne({ where: { id: group.id } }); } } export default Price;
JakeStanger/Reactive-Gallery
server/database/models/BasketItem.ts
import { Model, DataTypes, BelongsToSetAssociationMixin, } from "sequelize"; import Database from "../index"; import Image from "./Image"; import User from "./User"; import Price from "./Price"; class BasketItem extends Model { public id: number; public quantity: number; public framed: boolean; public image: Image; public user: User; public price: Price; public setImage!: BelongsToSetAssociationMixin<Image, "image">; public setUser!: BelongsToSetAssociationMixin<User, "user">; public setPrice!: BelongsToSetAssociationMixin<Price, "price">; public static load() { BasketItem.init( { id: { type: DataTypes.INTEGER.UNSIGNED, autoIncrement: true, primaryKey: true }, quantity: DataTypes.INTEGER, framed: DataTypes.BOOLEAN }, { sequelize: Database.getConnection(), tableName: "basket_item" } ); } public static async getFromObject(item: any): Promise<BasketItem> { return await BasketItem.findOne({ where: { id: item.id } }); } } export default BasketItem;
JakeStanger/Reactive-Gallery
server/database/index.ts
import { Sequelize, Dialect } from "sequelize"; class Database { private static _instance: Database; private _db: Sequelize; public static get() { if (Database._instance) return Database._instance; else { const instance = new Database(); Database._instance = instance; return instance; } } public static getConnection() { return Database.get()._db; } public async init() { const settings = process.env; const db = new Sequelize(settings.DATABASE_NAME, settings.DATABASE_USER, settings.DATABASE_PASSWORD, { host: settings.DATABASE_HOST, dialect: settings.DATABASE_DIALECT as Dialect, dialectOptions: { timezone: 'Etc/GMT0' }, define: { timestamps: false, underscored: true }, logging: settings.DATABASE_LOGGING === 'true' }); await new Promise((resolve, reject) => { db.authenticate() .then(() => { console.log("Connection has been established successfully."); this._db = db; resolve(); }) .catch(err => { console.error("Unable to connect to the database:", err); reject(); process.exit(1); }); }); } } export default Database;
JakeStanger/Reactive-Gallery
src/components/textField/ITextFieldProps.ts
interface ITextFieldProps { value: string; onChange: (value: string) => void; placeholder?: string; } export default ITextFieldProps;
JakeStanger/Reactive-Gallery
src/pages/upload/Upload.tsx
import React from "react"; import styles from "./Upload.module.scss"; import { FilePond, registerPlugin } from "react-filepond"; import FilePondImagePreview from "filepond-plugin-image-preview"; import FilePondValidateType from "filepond-plugin-file-validate-type"; import "filepond-plugin-image-preview/dist/filepond-plugin-image-preview.css"; import "filepond/dist/filepond.min.css"; import IUploadState from "./IUploadState"; import EditForm from "../../components/editForm/EditForm"; import { startCase } from "lodash"; import { RouteComponentProps } from "react-router-dom"; registerPlugin(FilePondImagePreview); registerPlugin(FilePondValidateType); class Upload extends React.Component<{}, IUploadState> { constructor(props: RouteComponentProps) { super(props); this.state = { file: null }; } private _onUpload = async ( _fieldName: string, file: File, _metadata: { [key: string]: any }, load: (p: string | { [key: string]: any }) => void, error: (errorText: string) => void, progress: (computable: boolean, loaded: number, total: number) => void, _abort: () => void ) => { try { progress(false, 0, 100); this.setState({ file, error: undefined }); load(file); progress(false, 100, 100); } catch (err) { error(err); this.setState({ error: err }); } }; public render() { const { file, error } = this.state; return ( <div> <FilePond acceptedFileTypes={["image/*"]} server={{ process: this._onUpload, revert: () => this.setState({ file: null, error: undefined }) }} /> <div className={styles.container}> {error && <div className={styles.error}>{JSON.parse(error).msg}</div>} </div> {file && ( <EditForm image={{ filename: file.name, name: startCase(file.name.split(".")[0]) }} mode="upload" file={file} onError={errorMsg => this.setState({ error: errorMsg })} history={(this.props as any).history} /> )} </div> ); } } export default Upload;
JakeStanger/Reactive-Gallery
src/services/eventService/EventService.ts
import IEvent from "./IEvent"; class EventService { private static _instance: EventService; public static getInstance(): EventService { if (EventService._instance) return EventService._instance; else { const instance = new EventService(); EventService._instance = instance; return instance; } } public async getAll(): Promise<IEvent[]> { const events = await fetch("/api/event").then(r => r.json()); if (events && !(events as any).msg) { return events; } else { console.error(events); return []; } } } export default EventService;
JakeStanger/Reactive-Gallery
src/services/basketService/IBasketItem.ts
import IImage from "../imageService/IImage"; import IPrice from "../priceService/IPrice"; interface IBasketItem { id: number; quantity: number; framed: boolean; image_id: number; user_id: number; price_id: number; image: IImage; price: IPrice; } export default IBasketItem;
JakeStanger/Reactive-Gallery
src/pages/preview/previewInfo/basketDialog/BasketDialog.tsx
<reponame>JakeStanger/Reactive-Gallery import React, { useCallback, useEffect, useRef, useState } from "react"; import styles from "./BasketDialog.module.scss"; import IBasketDialogProps from "./IBasketDialogProps"; import { range } from "lodash"; import Dropdown from "../../../../components/dropdown/Dropdown"; import Checkbox from "../../../../components/checkbox/Checkbox"; import PrimaryButton from "../../../../components/button/primary/PrimaryButton"; import { FontAwesomeIcon } from "@fortawesome/react-fontawesome"; import { faTimes, faCheckCircle } from "@fortawesome/free-solid-svg-icons"; import BasketService from "../../../../services/basketService/BasketService"; import Dialog from "../../../../components/dialog/Dialog"; const BasketDialog: React.FC<IBasketDialogProps> = ({ onDismiss, image, prices, history }) => { const basketService = useRef(BasketService.getInstance()); const [priceId, setPriceId] = useState<number>(prices[0]?.id); const [framed, setFramed] = useState(false); const [quantity, setQuantity] = useState(1); const [added, setAdded] = useState(false); const getPrice = useCallback(() => { const price = prices?.find(p => p.id === priceId); const priceValue = framed ? price?.framed : price?.unframed; return (priceValue || 0) * (quantity || 0); }, [prices, priceId, framed, quantity]); const addToBasket = useCallback(() => { const price = prices?.find(p => p.id === priceId); if (!price) throw new Error("Attempted to add to basket with no price set"); basketService.current .addToBasket(image, price, quantity, framed) .then(() => { setAdded(true); setTimeout(() => history.push('/basket'), 500); }) .catch(console.error); }, [framed, image, priceId, prices, quantity, history]); useEffect(() => { const price = prices?.find(p => p.id === priceId); if(price?.framed === null && framed) { setFramed(false); } }, [prices, priceId, framed]) return ( <Dialog isOpen={true} onDismiss={onDismiss}> <div className={styles.closeBtn} onClick={onDismiss}> <FontAwesomeIcon icon={faTimes} /> </div> <div className={styles.subTitle}>Add To Basket</div> {!added ? ( <div className={styles.form}> <label> <div>Size</div> <Dropdown value={priceId?.toString()} onChange={val => setPriceId(parseInt(val))} options={ prices?.map(price => ({ key: price.id.toString(), value: price.name })) || [] } /> </label> <label> Quantity <Dropdown value={quantity.toString()} onChange={val => setQuantity(parseInt(val))} options={range(1, 10).map(q => ({ key: q.toString(), value: q.toString() }))} /> </label> {prices.find(price => price.id === priceId)?.framed && <div> <Checkbox checked={framed} onChange={setFramed} label={image.priceGroup.name !== "Other" ? "Framed" : "Pack of 8"} /> </div>} <div className={styles.subSubTitle}>Price: £{getPrice().toFixed(2)}</div> <PrimaryButton onClick={addToBasket} text={"Add"} disabled={ priceId === undefined || !quantity || framed === undefined } /> </div> ) : ( <div style={{ textAlign: "center", fontSize: 100 }}> <FontAwesomeIcon icon={faCheckCircle} /> </div> )} </Dialog> ); }; export default BasketDialog;
JakeStanger/Reactive-Gallery
src/pages/preview/Preview.tsx
import React from "react"; import styles from "./Preview.module.scss"; import ImageService from "../../services/imageService/ImageService"; import IPreviewState from "./IPreviewState"; import IPreviewProps from "./IPreviewProps"; import Loader from "../../components/loader/Loader"; import PreviewInfo from "./previewInfo/PreviewInfo"; import UserService from "../../services/userService/UserService"; class Preview extends React.PureComponent<IPreviewProps, IPreviewState> { private _imageService: ImageService; private _userService: UserService; constructor(props: IPreviewProps) { super(props); this.state = { image: null, user: null }; this._imageService = ImageService.getInstance(); this._userService = UserService.getInstance(); } public componentDidMount() { const { filename } = this.props.match.params; this._imageService.get(filename).then(image => this.setState({ image })); this._userService.getCurrentUser().then(user => this.setState({ user })); } public render() { const { image, user } = this.state; const imageUrl = image ? this._imageService.getLink(image, true) : "#"; return ( <div> {image ? ( <div> <div className={styles.imageContainer}> <a href={imageUrl}> <img className={styles.image} src={imageUrl} alt={image.name} height={window.innerHeight * 0.8} /> </a> </div> <PreviewInfo image={image} user={user} history={this.props.history} /> </div> ) : ( <Loader /> )} </div> ); } } export default Preview;
JakeStanger/Reactive-Gallery
src/components/button/primary/IPrimaryButtonProps.ts
import IButtonProps from "../IButtonProps"; interface IPrimaryButtonProps extends IButtonProps { text: string; } export default IPrimaryButtonProps;
JakeStanger/Reactive-Gallery
src/pages/events/Events.tsx
<filename>src/pages/events/Events.tsx<gh_stars>0 import React, { useEffect, useState } from "react"; import styles from "./Events.module.scss"; import IEvent from "../../services/eventService/IEvent"; import EventService from "../../services/eventService/EventService"; import { DateTime } from "luxon"; const Events: React.FC = () => { const [events, setEvents] = useState<IEvent[] | null>(null); useEffect(() => { if (events === null) EventService.getInstance() .getAll() .then(setEvents); }, [events]); return ( <div className={styles.container}> <div className={styles.title}>Upcoming Events</div> <table style={{ width: "100%" }}> <thead> <tr className={styles.tableRow}> <th>Time</th> <th>Name</th> <th>Location</th> </tr> </thead> <tbody> {events && events.map((event: IEvent) => ( <tr> <td> {DateTime.fromISO(event.startTime).toFormat( "ccc dd LLL HH:mm" )}{" "} - {DateTime.fromISO(event.endTime).toFormat("HH:mm")} </td> <td>{event.name}</td> <td>{event.location}</td> </tr> ))} </tbody> </table> {!(events && events.length) && <div className={styles.subSubTitle}>There are currently no upcoming events</div>} </div> ); }; export default Events;
JakeStanger/Reactive-Gallery
src/services/checkoutService/CheckoutService.ts
import UserService from "../userService/UserService"; import ICheckoutSession from "./ICheckoutSession"; class CheckoutService { private static _instance: CheckoutService; private _userService: UserService; private constructor() { this._userService = UserService.getInstance(); } public static getInstance(): CheckoutService { if (CheckoutService._instance) return CheckoutService._instance; else { const instance = new CheckoutService(); CheckoutService._instance = instance; return instance; } } public async getPublicKey(): Promise<string> { const { publicKey } = await fetch("/api/checkout/public").then(r => r.json() ); return publicKey; } public async getSecretKey(post: boolean): Promise<string> { const response = await fetch("/api/checkout/secret", { method: "POST", headers: { Authorization: `Bearer ${UserService.getInstance().getToken()}`, "Content-Type": "application/json" }, body: JSON.stringify({ post }) }); const { sessionId } = await response.json(); return sessionId; } public async getSession(sessionId: string): Promise<ICheckoutSession> { const response = await fetch(`/api/checkout/session/${sessionId}`, { headers: { Authorization: `Bearer ${UserService.getInstance().getToken()}` } }); return await response.json(); } } export default CheckoutService;
JakeStanger/Reactive-Gallery
src/pages/gallery/IGalleryState.ts
import IImage from "../../services/imageService/IImage"; interface IGalleryState { loading: boolean; images: IImage[]; showLocation: boolean; showTime: boolean; showDescription: boolean; showTags: boolean; query: string; group: string; width: number; } export default IGalleryState;
JakeStanger/Reactive-Gallery
src/pages/pricing/Pricing.tsx
import React, { useEffect, useState } from "react"; import styles from "./Pricing.module.scss"; import IPriceGroup from "../../services/priceService/IPriceGroup"; import IPrice from "../../services/priceService/IPrice"; import PriceService from "../../services/priceService/PriceService"; import PriceTable from "./priceTable/PriceTable"; import TextPreamble from "../../pageContent/pricing/TextPreamble"; const Pricing: React.FC = () => { const [priceGroups, setPriceGroups] = useState<IPriceGroup[]>([]); const [prices, setPrices] = useState<IPrice[]>([]); useEffect(() => { PriceService.getInstance() .getAllPrices() .then(setPrices); PriceService.getInstance() .getAllPriceGroups() .then(setPriceGroups); }, []); return ( <div className={styles.container}> <div className={styles.title}>Pricing</div> <TextPreamble /> <div className={styles.groups}> {priceGroups.map((group, i) => { const w = group.ratioWidth; const h = group.ratioHeight; let aspectDiagram: JSX.Element | undefined; if (w && h) { const width = "40%"; const height = `calc(${width} * ${h / w}`; aspectDiagram = ( <div className={styles.diagramWrapper} style={{ width, paddingTop: height }} > <div className={styles.content}> <div className={styles.textWrapper}> <div> {group.ratioWidth}:{group.ratioHeight} </div> </div> </div> </div> ); } return ( <div key={group.id}> <div className={styles.subTitle}>{group.name}</div> <div className={styles.priceGroup}> <PriceTable group={group} prices={prices} /> <div className={styles.information}> {aspectDiagram} {group.description && <p>{group.description}</p>} </div> </div> </div> ); })} </div> </div> ); }; export default Pricing;
JakeStanger/Reactive-Gallery
server/tokenChecker.ts
<reponame>JakeStanger/Reactive-Gallery import jwt from "jsonwebtoken"; import { RequestHandler } from "express"; const tokenChecker: RequestHandler = (req, res, next) => { const token = req.headers.authorization && req.headers.authorization.split("Bearer ")[1]; // decode token if (token) { // verifies secret and checks exp jwt.verify(token, process.env.SESSION_SECRET, (err: any, decoded: string) => { if (err) { return res.status(401).json({ expired: true, msg: "Token expired" }); } (req as any).user = decoded; next(); }); } else { // if there is no token // return an error return res.status(403).send({ error: true, msg: "No token provided." }); } }; export default tokenChecker;
JakeStanger/Reactive-Gallery
src/pages/reports/Reports.tsx
<gh_stars>0 import React, { useCallback, useEffect, useState } from "react"; import styles from "./Reports.module.scss"; import IReportsProps from "./IReportsProps"; import IImage from "../../services/imageService/IImage"; import ImageService from "../../services/imageService/ImageService"; import { Link } from "react-router-dom"; const ImageLink: React.FC<{image: IImage}> = ({image}) => ( <div className={styles.imageLink}><Link to={`/preview/${image.id}`} target={'_blank'}>{image.name}</Link></div> ) const Reports: React.FC<IReportsProps> = () => { const [images, setImages] = useState<IImage[]>([]); const getImages = useCallback(() => { ImageService.getInstance() .getAll(true) .then(setImages) .catch(console.error); }, []) useEffect(() => { getImages(); const timer = setInterval(() => { getImages(); }, 10_000); return () => clearInterval(timer); }, [getImages]) return ( <div className={`${styles.container} ${styles.reports}`}> <div> <div className={styles.subSubTitle}>No Location</div> {images .filter(image => !image.location) .map(image => ( <ImageLink image={image} key={image.filename} /> ))} </div> <div> <div className={styles.subSubTitle}>No Tags</div> {images .filter(image => !image.tags?.length) .map(image => ( <ImageLink image={image} key={image.filename} /> ))} </div> <div> <div className={styles.subSubTitle}>No Price Group</div> {images .filter(image => (image as any).price_group_id === null) .map(image => ( <ImageLink image={image} key={image.filename} /> ))} </div> <div> <div className={styles.subSubTitle}>No Category</div> {images .filter(image => !image.categories?.length) .map(image => ( <ImageLink image={image} key={image.filename} /> ))} </div> <div> <div className={styles.subSubTitle}>Missing EXIF Data</div> {images .filter(image => !image.cameraModel) .map(image => ( <ImageLink image={image} key={image.filename} /> ))} </div> <div> <div className={styles.subSubTitle}>No Description</div> {images .filter(image => !image.description) .map(image => ( <ImageLink image={image} key={image.filename} /> ))} </div> <div> <div className={styles.subSubTitle}>Short Description</div> {images .filter(image => image.description && image.description.length <= 16) .map(image => ( <ImageLink image={image} key={image.filename} /> ))} </div> </div> ); }; export default Reports;
JakeStanger/Reactive-Gallery
server/utils/imageGenerator.ts
<reponame>JakeStanger/Reactive-Gallery import sharp from "sharp"; import * as path from "path"; import * as fs from "fs"; export async function generateThumbnail(buffer: Buffer, filename: string) { await sharp(buffer) .webp({ quality: 90 }) .resize(360, null) .toFile( path.join( process.env.UPLOAD_PATH, "thumb", filename.replace(/\.(.*)$/, ".webp") ) ); } export async function generateMarked(buffer: Buffer, filename: string) { let overlay = sharp( path.join(__dirname, "../", "../", "resources", "overlay.png") ); const image = await sharp(buffer); const { width, height } = await image.metadata(); overlay = overlay.resize({ withoutEnlargement: true, width, height }); const overlayBuffer = await overlay.toBuffer(); return await image .composite([ { input: overlayBuffer, gravity: sharp.gravity.northwest, tile: true } ]) .webp({ quality: 95, alphaQuality: 95 }) .toFile( path.join( process.env.UPLOAD_PATH, "marked", filename.replace(/\.(.*)$/, ".webp") ) ) .then(info => ({ width: info.width, height: info.height })); } /** * Generates a jpeg from a webp if required. * @param filename the webp filename * @param type marked or thumb image */ export async function generateJpeg(filename: string, type: "marked" | "thumb") { const filePath = path.join(process.env.UPLOAD_PATH, type, filename); const jpegPath = filePath.replace(/webp$/, "jpeg") if (fs.existsSync(jpegPath) || filePath === jpegPath) { return; } await sharp(filePath) .jpeg({ quality: 98 }) .toFile(jpegPath); }
JakeStanger/Reactive-Gallery
src/pages/pricing/priceTable/PriceTable.tsx
import React from "react"; import IPriceTableProps from "./IPriceTableProps"; import styles from "./PriceTable.module.scss"; const PriceTable: React.FC<IPriceTableProps> = ({ group, prices, className }) => { return ( <table className={className}> <thead> <tr className={styles.tableRow}> {group.name !== "Other" ? ( <> <th>Size</th> <th>Print Only</th> <th>Framed</th> </> ) : ( <> <th>Type</th> <th>Single</th> <th>Pack of 8</th> </> )} </tr> </thead> <tbody> {prices .filter(price => price.price_group_id === group.id) .map(price => ( <tr className={styles.tableRow} key={price.id}> <td>{price.name}</td> <td> £{price.unframed?.toFixed(2)} </td> <td> {price.framed && `£${price.framed?.toFixed(2)}`} </td> </tr> ))} </tbody> </table> ); }; export default PriceTable;
JakeStanger/Reactive-Gallery
server/database/models/Location.ts
import { Model, DataTypes } from "sequelize"; import Database from "../index"; import Image from "./Image"; class Location extends Model { public id: number; public name: string; public images?: Image[]; public static load() { Location.init( { id: { type: DataTypes.INTEGER.UNSIGNED, autoIncrement: true, primaryKey: true }, name: { type: DataTypes.STRING(32), unique: true } }, { sequelize: Database.getConnection(), tableName: "locations" } ); } public static async getFromObject(location: any): Promise<Location> { return await Location.findOrCreate({ where: { name: location.name } }).then(([location]) => location); } } export default Location;
JakeStanger/Reactive-Gallery
src/services/checkoutService/ICheckoutSession.ts
interface ICheckoutSessionItem { amount: number; currency: string; quantity: number; type: string; custom: { description: string; images: string[]; name: string; } } interface IAddress { city: string; country: string; line1: string; line2: string; postal_code: string; state: string; } interface ICheckoutSession { items: ICheckoutSessionItem[]; address: IAddress; name: string; } export default ICheckoutSession;
JakeStanger/Reactive-Gallery
server/StripeManager.ts
import { Stripe } from "stripe"; class StripeManager { private static _stripe: Stripe; public static getStripe() { if(this._stripe) { return this._stripe; } this._stripe = new Stripe(process.env.STRIPE_SECRET, { apiVersion: "2020-03-02" }); return this._stripe; } } export default StripeManager;
JakeStanger/Reactive-Gallery
server/routes/basketItem/BasketItem.ts
import { Request, Response } from "express"; import BasketItem from "../../database/models/BasketItem"; export const postBasketItem = async (req: Request, res: Response) => { const data = req.body; const [item, isNew] = await BasketItem.findOrCreate({where: { framed: data.framed, user_id: (req.user as any).id, image_id: data.image.id, price_id: data.price.id }}); if(data.quantity) { if(isNew) item.quantity = data.quantity; else item.quantity += data.quantity; await item.save(); } return res.status(201).json({msg: "success"}); }; export const deleteBasketItem = async (req: Request, res: Response) => { await BasketItem.destroy({where: {id: req.params.basketItemId}}); return res.status(201).json({msg: "success"}); }
JakeStanger/Reactive-Gallery
src/components/card/ICardProps.ts
import IImage from "../../services/imageService/IImage"; import ImageService from "../../services/imageService/ImageService"; import IBasketItem from "../../services/basketService/IBasketItem"; interface ICardProps { image: IImage; imageService: ImageService; height: number; showLocation: boolean; showTime: boolean; showTags: boolean; showDescription: boolean; showPriceInfo?: boolean; basketItem?: IBasketItem; onDelete?: (basketItem: IBasketItem) => void; query?: string; } export default ICardProps;
JakeStanger/Reactive-Gallery
src/styles/css.ts
const css = (...styles: any[]) => styles.filter(s => s).join(" "); export default css;
JakeStanger/Reactive-Gallery
src/services/imageService/IImage.ts
<filename>src/services/imageService/IImage.ts import ILocation from "./ILocation"; import ITag from "./ITag"; import IPriceGroup from "../priceService/IPriceGroup"; import ICategory from './ICategory'; interface IImage { id: number; description: string; filename: string; location: ILocation | null; name: string; categories: ICategory[]; tags: ITag[]; timeTaken: string; width: number; height: number; exposure: number; focalLength: number; aperture: number; iso: number; cameraModel: string; priceGroup: IPriceGroup; } export default IImage;
JakeStanger/Reactive-Gallery
src/pageContent/contact/TextPreamble.tsx
<filename>src/pageContent/contact/TextPreamble.tsx import React from "react"; import config from "../../config.json"; const TextPreamble: React.FC = () => ( <> <p> Email{" "} <a href={"mailto:" + config.contact.email}>{config.contact.email}</a>. Find us on <a href={config.contact.facebook}>Facebook</a> and{" "} <a href={config.contact.instagram}>Instagram</a> as rstangerphotography. We'll respond fastest through Facebook but will endeavor to respond as fast as possible. If you can't find what you're looking for, feel free to contact us and we will be happy to discuss any of your individual requirements. </p> </> ); export default TextPreamble;
JakeStanger/Reactive-Gallery
server/routes/basketItem/BasketItems.ts
<gh_stars>0 import { Request, Response } from "express"; import BasketItem from "../../database/models/BasketItem"; import Image from "../../database/models/Image"; import Price from "../../database/models/Price"; export async function getUserBasket(userId: number) { return await BasketItem.findAll({ where: { user_id: userId }, include: [ { model: Image, as: "image" }, { model: Price, as: "price" } ] }); } export const getBasket = async (req: Request, res: Response) => { const basket = await getUserBasket((req.user as any).id); return res.status(200).json(basket); }; export const clearBasket = async (req: Request, res: Response) => { await BasketItem.destroy({ where: { user_id: (req.user as any).id } }); return res.status(200).json({ msg: "success" }); };
JakeStanger/Reactive-Gallery
src/components/editForm/EditForm.tsx
import React from "react"; import styles from "./EditForm.module.scss"; import IEditFormProps from "./IEditFormProps"; import IEditFormState from "./IEditFormState"; import TagsInput, { Tag } from "react-tag-autocomplete"; import ILocation from "../../services/imageService/ILocation"; import ITag from "../..//services/imageService/ITag"; import ImageService from "../../services/imageService/ImageService"; import IImage from "../../services/imageService/IImage"; import Dropdown from "../dropdown/Dropdown"; import PriceService from "../../services/priceService/PriceService"; import Loader from "../loader/Loader"; import ICategory from "../../services/imageService/ICategory"; class EditForm extends React.PureComponent<IEditFormProps, IEditFormState> { private _imageService: ImageService; constructor(props: IEditFormProps) { super(props); this.state = { name: props.image.name || "", description: props.image.description || "", categories: props.image.categories || [], location: props.image.location ? [props.image.location] : null, tags: props.image.tags || [], suggestedCategories: [], suggestedLocations: [], suggestedTags: [], priceGroup: props.image.priceGroup, priceGroups: [], loading: false }; this._imageService = ImageService.getInstance(); this._removeCategory = this._removeCategory.bind(this); this._removeTag = this._removeTag.bind(this); } public componentDidMount() { const { priceGroup } = this.state; this._imageService .getLocations() .then(suggestedLocations => this.setState({ suggestedLocations })); this._imageService .getTags() .then(suggestedTags => this.setState({ suggestedTags })); this._imageService .getCategories() .then(suggestedCategories => this.setState({ suggestedCategories })); PriceService.getInstance() .getAllPriceGroups() .then(priceGroups => this.setState({ priceGroups, priceGroup: priceGroup ? priceGroup : priceGroups[0] }) ); } private _setName = (ev: React.ChangeEvent<HTMLInputElement>) => { this.setState({ name: ev.target.value }); }; private _setDescription = (ev: React.ChangeEvent<HTMLTextAreaElement>) => { this.setState({ description: ev.target.value }); }; private _setLocation = (location: Tag) => { this.setState({ location: [location as ILocation] }); }; private _clearLocation = (_index: number) => { this.setState({ location: null }); }; private _addCategory = (category: Tag) => { let { categories } = this.state; categories = [...categories, category as ICategory]; this.setState({ categories }); }; private _removeCategory(index: number) { let { categories } = this.state; categories = categories.filter((_, i) => i !== index); this.setState({ categories }); } private _addTag = (tag: Tag) => { let { tags } = this.state; tags = [...tags, tag as ITag]; this.setState({ tags }); }; private _removeTag = (index: number) => { let { tags } = this.state; tags = tags.filter((_, i) => i !== index); this.setState({ tags }); }; private _setPriceGroup = (priceGroupId: string) => { const groupId = parseInt(priceGroupId); const { priceGroups } = this.state; this.setState({ priceGroup: priceGroups.find(group => group.id === groupId)! }); }; private _onSave = async (ev: React.FormEvent) => { ev.preventDefault(); this.setState({ loading: true }); try { const { image, mode, file, history } = this.props; const { name, description, location, categories, tags, priceGroup } = this.state; if (mode === "upload" && file) { const res = await this._imageService.upload(file, { name, description, location: location ? location[0] : null, categories, tags, priceGroup }); if ((res as { msg: string }).msg && this.props.onError) this.props.onError((res as { msg: string }).msg); else history.push("/"); } else { await this._imageService.update({ id: image.id, filename: image.filename, name, description, location: location ? location[0] : null, tags, categories, priceGroup }); window.location.reload(); } } catch (err) { console.error(err); if (this.props.onError) this.props.onError(err.message); } this.setState({ loading: false }); }; private _onDelete = async (ev: React.FormEvent) => { ev.preventDefault(); await this._imageService.delete(this.props.image as IImage); this.props.history.push("/"); }; public render() { const { name, description, categories, location, tags, suggestedCategories, suggestedLocations, suggestedTags, priceGroup, priceGroups } = this.state; const { mode } = this.props; return ( <form onSubmit={this._onSave} className={styles.container}> <label> <div className={styles.label}>Name</div> <input value={name} onChange={this._setName} className={styles.name} /> </label> <label> <div className={styles.label}>Description</div> <textarea value={description} onChange={this._setDescription} rows={10} /> </label> <label> <div className={styles.label}>Categories</div> </label> <div> <TagsInput tags={categories} suggestions={ !categories || categories.length < 3 ? suggestedCategories.filter(c => !categories.includes(c)) : undefined } handleAddition={this._addCategory} handleDelete={this._removeCategory} placeholder={ !categories || categories.length < 3 ? "Press enter to confirm each category. Up to 3 categories." : "" } minQueryLength={0} autofocus={false} maxSuggestionsLength={20} /> </div> <label> <div className={styles.label}>Location</div> </label> <div> <TagsInput tags={location && location[0] ? location : undefined} suggestions={ !location || location.length < 1 ? suggestedLocations : undefined } handleAddition={this._setLocation} handleDelete={this._clearLocation} placeholder={!location ? "Press enter to confirm" : ""} allowNew autofocus={false} /> </div> <label> <div className={styles.label}>Tags</div> </label> <div> <TagsInput tags={tags} suggestions={!tags || tags.length < 10 ? suggestedTags : undefined} handleAddition={this._addTag} handleDelete={this._removeTag} placeholder={ !tags || tags.length < 10 ? "Press enter to confirm each tag. Up to 10 tags." : "" } allowNew autofocus={false} /> </div> <label> <div className={styles.label}>Price Group</div> </label> <div> <Dropdown value={priceGroup?.id} onChange={this._setPriceGroup} options={priceGroups.map(group => ({ key: group.id.toString(), value: group.name }))} /> </div> <div className={styles.buttons}> <button type="submit" className={styles.save}> {mode === "upload" ? "Upload" : "Save"} </button> {mode === "edit" && ( <button className={styles.delete} onClick={this._onDelete}> Delete </button> )} </div> {this.state.loading && <Loader small />} </form> ); } } export default EditForm;
JakeStanger/Reactive-Gallery
src/pages/checkout/Success.tsx
<reponame>JakeStanger/Reactive-Gallery import React, { useEffect, useState } from "react"; import styles from "./Checkout.module.scss"; import ICheckoutSession from "../../services/checkoutService/ICheckoutSession"; import CheckoutService from "../../services/checkoutService/CheckoutService"; import PrimaryButton from "../../components/button/primary/PrimaryButton"; import { RouteComponentProps } from "react-router-dom"; const Success: React.FC<RouteComponentProps> = ({history}) => { const [session, setSession] = useState<ICheckoutSession>(); useEffect(() => { const params = new URLSearchParams(window.location.search); if (params.has("session_id")) { CheckoutService.getInstance() .getSession(params.get("session_id")!) .then(setSession); } else { history.replace('/'); } }, [history]); return ( <div className={styles.container}> <div className={styles.title}>Thank You</div> <div> Thank you for making a purchase from Roger Stanger Photos, we hope you enjoy your order! Your order has been placed and you will receive a confirmation receipt email shortly. </div> <div> <PrimaryButton text={'Back to Gallery'} onClick={() => history.push('/')} /> </div> <div className={styles.row}> {session?.items && ( <div className={styles.items}> <div className={styles.subTitle}>Prints</div> <div className={styles.table}> {session.items.map(item => ( <React.Fragment key={item.custom.name}> <div>{item.custom.name}</div> <div>£{item.amount / 100}</div> <div>x{item.quantity}</div> <div>£{item.amount / 100 * item.quantity}</div> </React.Fragment> ))} <div>Total</div> <div></div> <div></div> <div>£{session.items.map(i => i.amount / 100 * i.quantity).reduce((total, amount) => total + amount)}</div> </div> </div> )} {session?.address && ( <div className={styles.address}> <div className={styles.subTitle}>Address</div> <div> <div>{session.name}</div> <div>{session.address.line1}</div> <div>{session.address.line2}</div> <div>{session.address.city}</div> <div>{session.address.state}</div> <div>{session.address.country}</div> <div>{session.address.postal_code}</div> </div> </div> )} </div> </div> ); }; export default Success;
JakeStanger/Reactive-Gallery
src/services/userService/UserService.ts
import Cookies from "js-cookie"; import IUser from "./IUser"; import React from "react"; class UserService { private static _instance: UserService; private _currentUser: IUser | null = null; constructor() { UserService._instance = this; } public static getInstance() { return UserService._instance; } public async init() { if (this.isLoggedIn()) await this.getCurrentUser(); } public getToken() { return Cookies.get("access_token"); } private _setToken(token: string) { Cookies.set("access_token", token); } public isLoggedIn() { const accessToken = this.getToken(); return ( !!accessToken && accessToken !== "undefined" ); } public async getCurrentUser(): Promise<IUser | null> { const accessToken = this.getToken(); if (!accessToken) return Promise.resolve(null); if (this._currentUser) return Promise.resolve(this._currentUser); let user = await fetch("/api/user", { headers: { Authorization: `Bearer ${accessToken}` } }).then(r => r.json()); if (!user || user.expired) { this.logout(); window.location.href = "/login"; // force refresh - probably not required eh return null; } if (user && user.username) { this._currentUser = user; return user; } return null; } public login = async ( ev: React.FormEvent, username: string, password: string ): Promise<string | null> => { ev.preventDefault(); const { accessToken, msg } = await fetch("/api/login", { method: "POST", body: JSON.stringify({ username, password }), headers: { "Content-Type": "application/json" } }).then(r => r.json()); if (accessToken) this._setToken(accessToken); return msg; } public logout() { Cookies.remove("access_token"); this._currentUser = null; } public signup = async (ev: React.FormEvent, username: string, password: string, email: string): Promise<string | null> => { ev.preventDefault(); const { accessToken, msg } = await fetch("/api/signup", { method: "POST", body: JSON.stringify({username, password, email}), headers: { "Content-Type": "application/json" } }).then(r => r.json()); if(accessToken) this._setToken(accessToken); return msg; } } export default UserService;
JakeStanger/Reactive-Gallery
src/services/priceService/IPrice.ts
interface IPrice { id: number; name: string; price_group_id: number; framed: number; unframed: number; postage: number; } export default IPrice;
JakeStanger/Reactive-Gallery
src/index.tsx
<gh_stars>0 import "react-app-polyfill/ie11"; import "react-app-polyfill/stable"; import React from "react"; import ReactDOM from "react-dom"; import App from "./App"; import * as serviceWorker from "./serviceWorker"; import UserService from "./services/userService/UserService"; import routes from "./routes/Routes"; import IUser from "./services/userService/IUser"; import IPermissionSet from "./services/userService/IPermissionSet"; import * as Sentry from "@sentry/react"; import { Integrations } from "@sentry/tracing"; import * as config from "./config.json"; Sentry.init({ dsn: config.sentry, autoSessionTracking: true, integrations: [new Integrations.BrowserTracing()], // We recommend adjusting this value in production, or using tracesSampler // for finer control tracesSampleRate: 1.0, }); const hasPermission = ( user: IUser | null, permissions: Partial<IPermissionSet> ): boolean => { for (let permission of Object.keys(permissions) as any[]) { if (!user || !user.permissions[permission as keyof IPermissionSet]) return false; } return true; }; /** * Checks if the browser supports webp. * Official method from Google. * @param feature * @private */ async function checkWebpFeature( feature: "lossy" | "lossless" | "alpha" | "animation" ): Promise<boolean> { return new Promise(resolve => { const kTestImages = { lossy: "UklGRiIAAABXRUJQVlA4IBYAAAAwAQCdASoBAAEADsD+JaQAA3AAAAAA", lossless: "UklGRhoAAABXRUJQVlA4TA0AAAAvAAAAEAcQERGIiP4HAA==", alpha: "UklGRkoAAABXRUJQVlA4WAoAAAAQAAAAAAAAAAAAQUxQSAwAAAARBxAR/Q9ERP8DAABWUDggGAAAABQBAJ0BKgEAAQAAAP4AAA3AAP7mtQAAAA==", animation: "UklGRlIAAABXRUJQVlA4WAoAAAASAAAAAAAAAAAAQU5JTQYAAAD/////AABBTk1GJgAAAAAAAAAAAAAAAAAAAGQAAABWUDhMDQAAAC8AAAAQBxAREYiI/gcA" }; const img = new Image(); img.onload = function() { const result = img.width > 0 && img.height > 0; resolve(result); }; img.onerror = function() { resolve(false); }; img.src = "data:image/webp;base64," + kTestImages[feature]; }); } const userService = new UserService(); userService .init() .then(async () => { const user = await userService.getCurrentUser().catch(); const filteredRoutes = routes.filter( route => !route.permissions || hasPermission(user, route.permissions) ); Sentry.setUser({ username: user?.username, email: user?.email }); const supportsWebp = await checkWebpFeature("lossy"); sessionStorage.setItem("supportsWebp", supportsWebp.toString()); ReactDOM.render( <App userService={userService} routes={filteredRoutes} />, document.getElementById("root") ); }) .catch(err => { document.body.innerHTML = ` <p style="padding: 10px;">An error occurred while trying to communicate with the server. This is most likely due to a temporary outage. Please refresh and try again.</p> <p style="padding: 10px;">If the issue persists please <a href="mailto:<EMAIL>">let the site administrator know</a>.</p> `; throw err; }); // If you want your app to work offline and load faster, you can change // unregister() to register() below. Note this comes with some pitfalls. // Learn more about service workers: https://bit.ly/CRA-PWA serviceWorker.unregister();
JakeStanger/Reactive-Gallery
src/raw.macro.d.ts
declare module "raw.macro" { export default (path: string) => string; }
JakeStanger/Reactive-Gallery
src/components/dialog/Dialog.tsx
<gh_stars>0 import React from "react"; import styles from "./Dialog.module.scss"; import IDialogProps from "./IDialogProps"; import { FontAwesomeIcon } from "@fortawesome/react-fontawesome"; import { faTimes } from "@fortawesome/free-solid-svg-icons"; const Dialog: React.FC<IDialogProps> = ({ isOpen, onDismiss, children }) => { return isOpen ? ( <div className={styles.modal} onClick={onDismiss}> <div className={styles.dialog} onClick={ev => ev.stopPropagation()}> <div className={styles.closeBtn} onClick={onDismiss}> <FontAwesomeIcon icon={faTimes} /> </div> {children} </div> </div> ) : null; }; export default Dialog;
imdfl/mutation-summary
src/mutation-summary-interface.d.ts
export interface IStringMap<T> { [key: string]: T; } export interface IMutationSummarySelector { qualifiers: IMutationSummaryQualifier[]; } export interface IChildListChange { } export interface IMutationSummaryQualifier { attrName: string; matches(oldValue: string): boolean; } export interface IMutationSummaryQuery { element?: string; attribute?: string; all?: boolean; characterData?: boolean; elementAttributes?: string; // if false, ignore the class attribute when observing attribute changes classAttribute?: boolean; attributeList?: string[]; elementFilter?: IMutationSummarySelector[]; } export interface IMutationSummaryInit { callback: (summaries: IMutationSummaryData[]) => void; queries: IMutationSummaryQuery[]; rootNode?: Node; /** * a function that filters mutation records before * they are passed to the summary engine * */ mutationFilter?: (rec: MutationRecord) => boolean; oldPreviousSibling?: boolean; observeOwnChanges?: boolean; } export interface IMutationSummaryConstructor { new(opts: IMutationSummaryInit, observe: boolean): IMutationSummary; } interface IMutationProjectionConstructor { new(rootNode: Node, mutations: MutationRecord[], selectors: IMutationSummarySelector[], calcReordered: boolean, calcOldPreviousSibling: boolean): IMutationProjection; } export interface IMutationProjection { processMutations(): any; ensureHasOldPreviousSiblingIfNeeded(node: Node): any; getChanged(summary: IMutationSummaryData, selectors: IMutationSummarySelector[], characterDataOnly: boolean): void; getOldParentNode(node: Node): Element; getOldPreviousSibling(node: Node): Node; getOldAttribute(element: Node, attrName: string): string; attributeChangedNodes(includeAttributes: string[]): IStringMap<Element[]>; getOldCharacterData(node: Node): string; getCharacterDataChanged(): Node[]; getChildlistChange(el: Element): IChildListChange; processChildlistChanges(): any; wasReordered(node: Node): void; } export interface IMutationSummaryDataConstructor { new(projection: IMutationProjection, query: IMutationSummaryQuery): IMutationSummaryData; } export interface IMutationSummaryData { added: Node[]; removed: Node[]; reparented: Node[]; reordered: Node[]; valueChanged: Node[]; attributeChanged: IStringMap<Element[]>; characterDataChanged: Node[]; getOldParentNode(node: Node): Element; getOldAttribute(node: Node, name: string): string; getOldCharacterData(node: Node): string ; getOldPreviousSibling(node: Node): Node; getOldCharacterData(node: Node): string; getCharacterDataChanged(): Node[]; } export interface IMutationSummary { disconnect(): IMutationSummaryData[]; reconnect(): void; takeSummaries(): IMutationSummaryData[]; }
Mabloq/mabloq-notion
app/src/block/utils/type-guards/parent-types.ts
import { DatabaseParentDto } from 'src/block/dto/extra-models/parents/database-parent.dto'; import { PageParentDto } from 'src/block/dto/extra-models/parents/page-parent.dto'; import { WorkspaceParentDto } from 'src/block/dto/extra-models/parents/workspace-parent.dto'; export function isDatabaseParent( parent: DatabaseParentDto | PageParentDto | WorkspaceParentDto, ): parent is DatabaseParentDto { return (parent as DatabaseParentDto).database_id !== undefined; } export function isPageParent( parent: DatabaseParentDto | PageParentDto | WorkspaceParentDto, ): parent is PageParentDto { return (parent as PageParentDto).page_id !== undefined; } // export function isPageParentt<T>( // iSearchResultRes: ISearchResults<T> | MessageTrace, // ): iSearchResultRes is ISearchResults<T> { // return (iSearchResultRes as ISearchResults<T>) !== undefined; // }
Mabloq/mabloq-notion
app/src/block/interfaces/blocks/heading1.interface.ts
import { BaseBlockInterface } from '../block.interface'; import { RichTextInterface } from '../common/rich-text.interface'; export interface Heading1Interface { color: string; rich_text: RichTextInterface[]; } export interface Heading1BlockInterface extends BaseBlockInterface { heading_1: Heading1Interface; }
Mabloq/mabloq-notion
app/src/block/dto/database/create-database.dto.ts
<reponame>Mabloq/mabloq-notion<filename>app/src/block/dto/database/create-database.dto.ts<gh_stars>0 import { ApiProperty, getSchemaPath } from '@nestjs/swagger'; import { DatabaseInterface } from 'src/block/interfaces/database.interface'; import { FileObjectInterface } from 'src/block/interfaces/common/file-object.interface'; import { FileObjectDto } from '../extra-models/common/file-object.dto'; import { RichTextDto } from '../extra-models/common/rich-text.dto'; import { PropertyConfigInterface } from 'src/block/interfaces/properties/property.interface'; import { NumberConfigDto } from '../extra-models/properties/property-config/number-config.dto'; import { SelectConfigDto } from '../extra-models/properties/property-config/select-config-interface.dto'; import { ParentInerface } from 'src/block/interfaces/common/parent.interface'; import { DatabaseParentDto } from '../extra-models/parents/database-parent.dto'; import { PageParentDto } from '../extra-models/parents/page-parent.dto'; import { WorkspaceParentDto } from '../extra-models/parents/workspace-parent.dto'; export class CreateDatabaseDto implements Partial<DatabaseInterface> { @ApiProperty({ required: true }) object: string; @ApiProperty({ items: { $ref: getSchemaPath(FileObjectDto) } }) cover?: FileObjectInterface; @ApiProperty({ items: { $ref: getSchemaPath(FileObjectDto) } }) icon?: FileObjectInterface; @ApiProperty() archived?: boolean; @ApiProperty() created_time: string; @ApiProperty() parent_id?: string; @ApiProperty({ type: 'object', anyOf: [ { $ref: getSchemaPath(DatabaseParentDto) }, { $ref: getSchemaPath(PageParentDto) }, { $ref: getSchemaPath(WorkspaceParentDto) }, ], }) parent?: ParentInerface; @ApiProperty({ type: 'object', additionalProperties: { anyOf: [ { $ref: getSchemaPath(RichTextDto) }, { $ref: getSchemaPath(NumberConfigDto) }, { $ref: getSchemaPath(SelectConfigDto) }, ], }, }) properties: { [key: string | symbol]: PropertyConfigInterface; title: PropertyConfigInterface; }; }
Mabloq/mabloq-notion
app/src/block/dto/extra-models/properties/property-config/number-config.dto.ts
import { ApiProperty } from '@nestjs/swagger'; import { NumberConfigInterface } from 'src/block/interfaces/properties/property-config/number-config.interface'; export enum NumberConfigEnum { NUMBER = 'number', DOLLAR = 'dollar', NUMBER_WITH_COMMAS = 'number_with_commas', PERCENT = 'percent', } export class NumberConfigDto implements NumberConfigInterface { @ApiProperty({ type: 'string', enum: Object.values(NumberConfigEnum) }) format: NumberConfigEnum; }
Mabloq/mabloq-notion
app/src/block/schemas/parents/page-parent.schema.ts
import { Prop, Schema, SchemaFactory } from '@nestjs/mongoose'; @Schema({ _id: false }) export class PageParent { @Prop() database_id: string; } export const PageParentSchema = SchemaFactory.createForClass(PageParent);
Mabloq/mabloq-notion
app/src/block/dto/extra-models/properties/property-types/title-property.dto.ts
import { ApiExtraModels, ApiProperty, getSchemaPath } from '@nestjs/swagger'; import { RichTextInterface } from 'src/block/interfaces/common/rich-text.interface'; import { TitlePropertyInterface } from 'src/block/interfaces/properties/property-types/title-property.interface'; import { RichTextDto } from '../../common/rich-text.dto'; @ApiExtraModels(RichTextDto) export class TitlePropertyDto implements TitlePropertyInterface { @ApiProperty({ default: 'title' }) type: 'title'; @ApiProperty({ type: 'object', additionalProperties: { $ref: getSchemaPath(RichTextDto), }, }) title: RichTextInterface[]; }
Mabloq/mabloq-notion
app/src/block/dto/extra-models/properties/property-types/multi-select-property.dto.ts
<reponame>Mabloq/mabloq-notion<filename>app/src/block/dto/extra-models/properties/property-types/multi-select-property.dto.ts import { ApiExtraModels, ApiProperty, getSchemaPath } from '@nestjs/swagger'; import { MultiSelectPropertyInterface } from 'src/block/interfaces/properties/property-types/multi-select-property.interface'; @ApiExtraModels() export class SelectNameDto { @ApiProperty() name: string; } @ApiExtraModels() export class MultiSelectPropertyDto implements MultiSelectPropertyInterface { @ApiProperty({ default: 'multi_select' }) type: 'multi_select'; @ApiProperty({ type: 'array', items: { type: 'object', additionalProperties: { $ref: getSchemaPath(SelectNameDto), }, }, }) multi_select: Array<{ name: string }>; }
Mabloq/mabloq-notion
app/src/block/dto/extra-models/common/rich-text.dto.ts
<reponame>Mabloq/mabloq-notion<gh_stars>0 import { ApiProperty, ApiExtraModels } from '@nestjs/swagger'; import { RichTextInterface } from 'src/block/interfaces/common/rich-text.interface'; import { AnnotationDto } from './annotations.dto'; import { TextDto } from './text.dto'; @ApiExtraModels(AnnotationDto, TextDto) export class RichTextDto implements RichTextInterface { @ApiProperty({ default: 'rich_text', required: true, }) type: 'rich_text'; @ApiProperty() plain_text: string; @ApiProperty({ required: true }) text: TextDto; @ApiProperty({ required: false }) annotation?: AnnotationDto; }
Mabloq/mabloq-notion
app/src/block/interfaces/properties/property-config/number-config.interface.ts
type NumberFormat = 'number' | 'dollar' | 'number_with_commas' | 'percent'; export interface NumberConfigInterface { type: 'number'; format: NumberFormat; }
Mabloq/mabloq-notion
app/src/block/services/block.service.ts
<reponame>Mabloq/mabloq-notion<gh_stars>0 import { Injectable, Post } from '@nestjs/common'; import { CreateBlockDto } from '../dto/create-block.dto'; import { Model, FilterQuery } from 'mongoose'; import { InjectModel } from '@nestjs/mongoose'; import { Block, BlockDocument } from '../schemas/block.schema'; import { ParagraphBlock, ParagraphBlockDocument, } from '../schemas/blocks/paragraph.schema'; @Injectable() export class BlockService { constructor(@InjectModel(Block.name) private blockModel: Model<Block>) {} async insertOne(createBlockDto: CreateBlockDto): Promise<Block> { const createdBlock = await this.blockModel.create(createBlockDto); return createdBlock.save(); } async findMany(blockIds: string[]) { const findQuery: FilterQuery<Block> = { _id: { $in: blockIds, }, }; const fetchedBlocks = await this.blockModel.find(findQuery).exec(); return fetchedBlocks; } async findOne(id: string) { return await this.blockModel.findById(id); } async findAll() { return await this.blockModel.find({}).limit(10); } update(id: number) { return `This action updates a #${id} block`; } remove(id: number) { return `This action removes a #${id} block`; } }
Mabloq/mabloq-notion
app/src/block/schemas/properties/property-config/number-config-schema.ts
import { Prop, Schema, SchemaFactory } from '@nestjs/mongoose'; import { Document } from 'mongoose'; export enum FormatEnum { NUMBER = 'number', DOLLAR = 'dollar', NUMBER_WITH_COMMAS = 'number_with_commas', PERCENT = 'percent', } @Schema() export class NumberConfig { @Prop({ type: String, enum: Object.values(FormatEnum), required: true, message: '{VALUE} is not supported', }) format: string; } export const NumberConfigSchema = SchemaFactory.createForClass(NumberConfig); export type NumberConfigDocument = NumberConfig & Document;
Mabloq/mabloq-notion
app/src/block/interfaces/properties/property-types/rich-text-property.interface.ts
import { RichTextInterface } from '../../common/rich-text.interface'; export interface RichTextPropertyInterface { type: 'rich_text'; rich_text: RichTextInterface[]; }
Mabloq/mabloq-notion
app/src/block/interfaces/common/annotation.interface.ts
<gh_stars>0 export interface AnnotationInterface { bold: boolean; italic: boolean; strikethrough: boolean; underline: boolean; code: boolean; }
Mabloq/mabloq-notion
app/src/block/interfaces/properties/property.interface.ts
<filename>app/src/block/interfaces/properties/property.interface.ts<gh_stars>0 import { NumberConfigInterface } from './property-config/number-config.interface'; import { SelectConfigInterface } from './property-config/select-config.interface'; import { MultiSelectPropertyInterface } from './property-types/multi-select-property.interface'; import { NumberPropertyInterface } from './property-types/number-property.interface'; import { RichTextPropertyInterface } from './property-types/rich-text-property.interface'; import { SelectPropertyInterface } from './property-types/select-property.interface'; import { TitlePropertyInterface } from './property-types/title-property.interface'; type PropertyType = 'rich_text' | 'number' | 'select' | 'multi_select'; export interface BasePropertyInterface { object: 'property_item'; id: string; type: PropertyType; } export interface PropertiesInterface { title: PropertyInterface; [key: string | symbol]: PropertyInterface; } export interface PropertiesConfigInterface { title: PropertyConfigInterface; [key: string | symbol]: PropertyConfigInterface; } export type PropertyInterface = | TitlePropertyInterface | RichTextPropertyInterface | NumberPropertyInterface | SelectPropertyInterface | MultiSelectPropertyInterface; export type PropertyConfigInterface = | RichTextPropertyInterface | NumberConfigInterface | SelectConfigInterface;
Mabloq/mabloq-notion
app/src/block/schemas/properties/property-types/number-property.schema.ts
import { Prop, Schema, SchemaFactory } from '@nestjs/mongoose'; import { Document } from 'mongoose'; @Schema() export class NumberProperty { @Prop({ _id: false, type: Number }) number: number; } export const NumberPropertySchema = SchemaFactory.createForClass(NumberProperty); export type NumberPropertyDocument = NumberProperty & Document;
Mabloq/mabloq-notion
app/src/block/interfaces/common/text.interface.ts
export interface TextInterface { text: string; link?: string; }
Mabloq/mabloq-notion
app/src/block/schemas/properties/property-type.enum.ts
export enum PropertyTypeEnum { TITLE = 'title', RICH_TEXT = 'rich_text', NUMBER = 'number', SELECT = 'select', DATE = 'date', }
Mabloq/mabloq-notion
app/src/block/schemas/properties/property-types/title-property.schema.ts
<filename>app/src/block/schemas/properties/property-types/title-property.schema.ts import { Prop, Schema, SchemaFactory } from '@nestjs/mongoose'; import { Document } from 'mongoose'; import { RichTextSchema, RichText } from '../../common/rich-text.schema'; @Schema() export class TitleProperty { @Prop({ _id: false, type: [RichTextSchema] }) title: RichText[]; } export const TitlePropertySchema = SchemaFactory.createForClass(TitleProperty); export type TitlePropertyDocument = TitleProperty & Document;
Mabloq/mabloq-notion
app/src/block/schemas/block.schema.ts
<filename>app/src/block/schemas/block.schema.ts import { Prop, Schema, SchemaFactory } from '@nestjs/mongoose'; import mongoose from 'mongoose'; import { Document } from 'mongoose'; import { BaseBlockInterface } from '../interfaces/block.interface'; import { BlockEnum, BlockType } from './common/block-enum'; import { ObjectEnum } from './common/object-enum'; export type BlockDocument = Block & Document; @Schema({ discriminatorKey: 'type', timestamps: { createdAt: 'created_time', updatedAt: 'last_edited_time' }, }) export class Block implements BaseBlockInterface { @Prop({ type: String, required: true, enum: Object.values(ObjectEnum), message: '{VALUE} is not supported', }) object!: ObjectEnum.BLOCK; @Prop({ type: String, required: true, enum: Object.values(BlockEnum), message: '{VALUE} is not supported', }) type!: BlockType; @Prop() updated_by: string; //TODO: Partial<User> @Prop() has_children: boolean; @Prop({ type: [{ type: mongoose.Schema.Types.ObjectId, ref: 'Block' }], required: false, }) children: string[]; @Prop({ type: Date, }) created_time: string; @Prop({ type: Date, }) last_edited_time: string; } export const BlockSchema = SchemaFactory.createForClass(Block);
Mabloq/mabloq-notion
app/src/block/utils/page-validators/validators/database-parent-validator.ts
import { CreatePageDto } from '../../../dto/page/create-page.dto'; import IPageValidator from '../page-validator-interface'; import { PropertiesInterface, PropertiesConfigInterface, } from '../../../interfaces/properties/property.interface'; import { isDatabaseParent } from '../../type-guards/parent-types'; import { Inject, Injectable } from '@nestjs/common'; import { DatabaseService } from '../../../services/database.service'; @Injectable() export default class DatabaseParentValidator implements IPageValidator { private createPageDto: CreatePageDto; @Inject(DatabaseService) private databaseService: DatabaseService; private onlyDatabaseProperties( pageProperites: PropertiesInterface, DatabaseProperties: PropertiesConfigInterface, ) { const pagePropertyeKeys = Object.keys(pageProperites); const databasePropertyKeys = Object.keys(DatabaseProperties); return pagePropertyeKeys.every((key) => databasePropertyKeys.includes(key)); } constructor(createPageDto: CreatePageDto) { this.createPageDto = createPageDto; } async validate(databaseProperties: PropertiesConfigInterface): Promise<void> { if (isDatabaseParent(this.createPageDto.parent)) { if ( !this.onlyDatabaseProperties( this.createPageDto.properties, databaseProperties, ) ) { const databaseFields = Object.keys(databaseProperties); const notIncludedInDatabaseConfig = Object.keys( this.createPageDto.properties, ).filter((pageField) => !databaseFields.includes(pageField)); throw new Error( `Invalid Field exception: {${notIncludedInDatabaseConfig.join( ', ', )}} not valid field(s) on database: {${databaseFields.join(', ')}}`, ); } } } }
Mabloq/mabloq-notion
app/src/block/tests/mocks/database/index.ts
<gh_stars>0 import { CreateDatabaseDto } from 'src/block/dto/database/create-database.dto'; import { DatabaseInterface } from 'src/block/interfaces/database.interface'; import { DatabaseDocument } from 'src/block/schemas/database.schema'; import { ParentInerface } from '../../../interfaces/common/parent.interface'; import { PropertiesConfigInterface } from '../../../interfaces/properties/property.interface'; import { HigherOrderBlockDocument } from '../../../schemas/higher-order-block.schema'; const dateIso = new Date().toISOString(); const mockBaseDatabase = ( id = 'a uuid', object = 'page', last_edited_by = 'mabloq', created_by = 'mabloq', ): Omit<DatabaseInterface, 'properties'> => ({ id, object, created_by, created_time: dateIso, last_edited_by, last_edited_time: dateIso, }); export const mockDatabase = ( id = 'a uuid', title = 'A Database Title', properties: PropertiesConfigInterface = { title: { type: 'rich_text', rich_text: [ { type: 'text', plain_text: title, text: { text: title }, }, ], }, valid_field: { type: 'number', format: 'number', }, }, ): DatabaseInterface => { const basePage = mockBaseDatabase(id); return { ...basePage, properties, }; }; export const mockDatabaseDto = ( id = 'a uuid', title = 'A Page Title', properties: PropertiesConfigInterface = { title: { type: 'rich_text', rich_text: [ { type: 'text', plain_text: title, text: { text: title }, }, ], }, valid_field: { type: 'number', format: 'number', }, }, parent: ParentInerface = { type: 'page', page_id: 'id-page-1' }, ): CreateDatabaseDto => { const basePage = mockBaseDatabase(id); return { ...basePage, properties, parent, }; }; export const mockDatabaseDocument = ( mock?: Partial<DatabaseInterface>, ): Partial<DatabaseDocument> => ({ _id: mock?.id || 'a uuid', object: mock?.object, icon: mock?.icon, cover: mock?.cover || { type: 'external', url: '' }, archived: mock?.archived || false, last_edited_by: mock?.last_edited_by || 'mabloq', parent: mock?.parent || { type: 'workspace', workspace_id: 'workspace-1' }, parent_id: mock?.parent_id || 'workspace-1', created_by: mock?.created_by || 'mabloq', created_time: mock?.created_time || dateIso, last_edited_time: mock?.last_edited_time || dateIso, properties: mock?.properties || { title: { type: 'rich_text', rich_text: [ { type: 'text', plain_text: 'hello world', text: { text: 'hello world' }, }, ], }, valid_field: { type: 'number', format: 'number', }, }, });
Mabloq/mabloq-notion
app/src/block/tests/mocks/blocks/index.ts
import { BaseBlockInterface, BlockInterface, ParagraphBlockInterface, CodeBlockInterface, Heading1BlockInterface, } from 'src/block/interfaces'; import { BlockDTOs } from 'src/block/dto/extra-models/block-models'; import { BlockDocument } from 'src/block/schemas/block.schema'; import { ParagraphBlockDocument } from 'src/block/schemas/blocks/paragraph.schema'; import { CodeBlockDocument } from 'src/block/schemas/blocks/code.schema'; import { BlockEnum } from 'src/block/schemas/common/block-enum'; import { ObjectEnum } from 'src/block/schemas/common/object-enum'; const dateIso = new Date().toISOString(); type BlockTypeInterface = | ParagraphBlockInterface | CodeBlockInterface | Heading1BlockInterface; type DiscriminatorInterface = | Pick<ParagraphBlockInterface, 'paragraph'> | Pick<CodeBlockInterface, 'code'>; type TypeEnum = 'paragraph' | 'code' | 'heading_1'; const mockBlock = ( id = 'a uuid', object = 'block', type = 'paragraph', created_time = dateIso, last_edited_time = dateIso, updated_by = 'mabloq', has_children = false, ): BaseBlockInterface => ({ id, object, type, updated_by, has_children, created_time, last_edited_time, }); export const mockParagraphBlock = ( id = 'a uuid', paragraphText = 'Hello There!', object = 'block', type: TypeEnum = 'paragraph', created_time = dateIso, last_edited_time = dateIso, updated_by = 'mabloq', has_children = false, ): ParagraphBlockInterface => { const baseBlock = mockBlock( id, object, type, created_time, last_edited_time, updated_by, has_children, ); return { ...baseBlock, paragraph: { rich_text: [ { plain_text: paragraphText, type: 'text', text: { text: paragraphText }, }, ], }, }; }; export const mockCodeBlock = ( id = 'a uuid', codeText = 'console.log("Hello World!")', created_time = dateIso, last_edited_time = dateIso, updated_by = 'mabloq', has_children = false, ): CodeBlockInterface => { const baseBlock = mockBlock( id, 'block', 'code', created_time, last_edited_time, updated_by, has_children, ); return { ...baseBlock, code: { rich_text: [ { plain_text: codeText, type: 'text', text: { text: codeText } }, ], language: 'javascript', }, }; }; export const mockParagraphBlockDocument = ( mock?: Partial<ParagraphBlockInterface>, ): Partial<BlockDocument | ParagraphBlockDocument> => ({ _id: mock?.id || 'a uuid', object: mock?.object, type: mock?.type || 'type', updated_by: mock?.updated_by || 'mabloq', created_time: mock?.created_time || dateIso, last_edited_time: mock?.last_edited_time || dateIso, has_children: mock?.has_children || false, paragraph: mock.paragraph, }); export const mockCodeBlockDocument = ( mock?: Partial<CodeBlockInterface>, ): Partial<BlockDocument | CodeBlockDocument> => ({ _id: mock?.id || 'a uuid', object: mock?.object, type: mock?.type || 'type', updated_by: mock?.updated_by || 'mabloq', created_time: mock?.created_time || dateIso, last_edited_time: mock?.last_edited_time || dateIso, has_children: mock?.has_children || false, code: mock.code, }); export const mapParagraphBlockArrToDocumentArr = ( blocks: ParagraphBlockInterface[], ) => blocks.map((block) => mockParagraphBlockDocument(block)); export const mapCodeBlockArrToDocumentArr = (blocks: CodeBlockInterface[]) => blocks.map((block) => mockCodeBlockDocument(block));
Mabloq/mabloq-notion
app/src/block/interfaces/common/file-object.interface.ts
<filename>app/src/block/interfaces/common/file-object.interface.ts export interface FileObjectInterface { type: string; url: string; }
Mabloq/mabloq-notion
app/src/block/utils/page-validators/page-validator-interface.ts
<gh_stars>0 export default interface IPageValidator { validate(data?: any): Promise<void>; }
Mabloq/mabloq-notion
app/src/block/dto/extra-models/parents/workspace-parent.dto.ts
<filename>app/src/block/dto/extra-models/parents/workspace-parent.dto.ts<gh_stars>0 import { ApiExtraModels, ApiProperty } from '@nestjs/swagger'; import { WorkspaceParentInterface } from 'src/block/interfaces/common/parent.interface'; @ApiExtraModels() export class WorkspaceParentDto implements WorkspaceParentInterface { @ApiProperty({ default: 'workspace', required: true, }) type: 'workspace'; @ApiProperty({ required: true }) workspace_id: string; }
Mabloq/mabloq-notion
app/src/block/dto/extra-models/parents/page-parent.dto.ts
import { ApiExtraModels, ApiProperty } from '@nestjs/swagger'; import { PageParentInterface } from 'src/block/interfaces/common/parent.interface'; @ApiExtraModels() export class PageParentDto implements PageParentInterface { @ApiProperty({ default: 'page', required: true, }) type: 'page'; @ApiProperty({ required: true }) page_id: string; }
Mabloq/mabloq-notion
app/src/block/schemas/blocks/file.schema.ts
import { Prop, Schema, SchemaFactory } from '@nestjs/mongoose'; import { Document } from 'mongoose'; import { FileObjectSchema } from '../common/file-object.schema'; import { FileObjectInterface } from 'src/block/interfaces/common/file-object.interface'; import { FileBlockInterface } from 'src/block/interfaces/blocks/file.interface'; export type FileBlockDocument = FileBlock & Document; @Schema({ _id: false }) export class FileBlock implements FileBlockInterface { object: string; type: string; updated_by: string; created_time: string; last_edited_time: string; has_children: boolean; @Prop({ type: FileObjectSchema, required: true }) file: FileObjectInterface; } export const FileBlockSchema = SchemaFactory.createForClass(FileBlock);
Mabloq/mabloq-notion
app/src/block/interfaces/blocks/code.interface.ts
import { BaseBlockInterface } from '../block.interface'; import { RichTextInterface } from '../common/rich-text.interface'; export interface CodeInterface { language: string; rich_text: RichTextInterface[]; } export interface CodeBlockInterface extends BaseBlockInterface { code: CodeInterface; }
Mabloq/mabloq-notion
app/src/block/dto/extra-models/common/file-object.dto.ts
<reponame>Mabloq/mabloq-notion<filename>app/src/block/dto/extra-models/common/file-object.dto.ts import { ApiProperty } from '@nestjs/swagger'; export class FileObjectDto { @ApiProperty({ default: 'external', required: true, }) type: 'external'; @ApiProperty({ required: true }) url: string; }
Mabloq/mabloq-notion
app/src/block/dto/extra-models/common/text.dto.ts
<reponame>Mabloq/mabloq-notion<filename>app/src/block/dto/extra-models/common/text.dto.ts import { ApiExtraModels, ApiProperty } from '@nestjs/swagger'; import { TextInterface } from 'src/block/interfaces/common/text.interface'; @ApiExtraModels() export class TextDto implements TextInterface { @ApiProperty({ type: 'string', required: true, }) text: string; @ApiProperty({ type: 'string', required: false, }) link?: string; }
Mabloq/mabloq-notion
app/src/block/schemas/common/image.schema.ts
<reponame>Mabloq/mabloq-notion<filename>app/src/block/schemas/common/image.schema.ts import { Prop, Schema, SchemaFactory, raw } from '@nestjs/mongoose'; import { Document } from 'mongoose'; export type ImageDocument = Image & Document; export type ImageBlockDocument = ImageBlock & Document; @Schema({ _id: false }) export class Image { @Prop() type: 'external'; @Prop(raw({ url: { type: String, required: true } })) external: { url: string }; } export const ImageSchema = SchemaFactory.createForClass(Image); @Schema({ _id: false }) export class ImageBlock { @Prop({ type: ImageSchema, required: true }) image: Image; } export const ImageBlockSchema = SchemaFactory.createForClass(ImageBlock);
Mabloq/mabloq-notion
app/src/block/schemas/properties/property-config/select-config-schema.ts
import { Prop, Schema, SchemaFactory, raw } from '@nestjs/mongoose'; import { Document } from 'mongoose'; import { randomIdGenerator } from 'src/block/utils/random-id-generator'; @Schema() export class SelectOption { @Prop({ default: () => randomIdGenerator(4) }) id: string; @Prop() color: string; @Prop() name: string; } export const SelectOptionSchema = SchemaFactory.createForClass(SelectOption); export type SelectOptionDocument = SelectOption & Document; @Schema() export class SelectConfig { @Prop( raw({ name: { type: String, required: true }, }), ) options: [SelectOption]; } export const SelectConfigSchema = SchemaFactory.createForClass(SelectConfig); export type SelectConfigDocument = SelectConfig & Document;
Mabloq/mabloq-notion
app/src/block/schemas/blocks/image.schema.ts
import { Prop, Schema, SchemaFactory } from '@nestjs/mongoose'; import { Document } from 'mongoose'; import { FileObjectSchema } from '../common/file-object.schema'; import { FileObjectInterface } from 'src/block/interfaces/common/file-object.interface'; import { ImageBlockInterface } from 'src/block/interfaces/blocks/image.interface'; export type ImageBlockDocument = ImageBlock & Document; @Schema({ _id: false }) export class ImageBlock implements ImageBlockInterface { object: string; type: string; updated_by: string; created_time: string; last_edited_time: string; has_children: boolean; @Prop({ type: FileObjectSchema, required: true }) image: FileObjectInterface; } export const ImageBlockSchema = SchemaFactory.createForClass(ImageBlock);
Mabloq/mabloq-notion
app/src/block/controllers/block.controller.ts
<gh_stars>0 import { Controller, Get, Post, Body, Patch, Param, Delete, } from '@nestjs/common'; import { BlockService } from '../services/block.service'; import { CreateBlockDto } from '../dto/create-block.dto'; @Controller('/api/rest/v1/block') export class BlockController { constructor(private readonly blockService: BlockService) {} @Post() create(@Body() createBlockDto: CreateBlockDto) { return this.blockService.insertOne(createBlockDto); } @Get() findAll() { return this.blockService.findAll(); } @Get(':id') findOne(@Param('id') id: string) { return this.blockService.findOne(id); } // @Patch(':id') // update(@Param('id') id: string, @Body() updateBlockDto: UpdateBlockDto) { // return this.blockService.update(+id, updateBlockDto); // } @Delete(':id') remove(@Param('id') id: string) { return this.blockService.remove(+id); } }
Mabloq/mabloq-notion
app/src/block/tests/mocks/blocks/paragraph.mock.ts
import { BaseBlockInterface, BlockInterface, ParagraphBlockInterface, CodeBlockInterface, Heading1BlockInterface, } from 'src/block/interfaces'; import { BlockDTOs } from 'src/block/dto/extra-models/block-models'; import { BlockDocument } from 'src/block/schemas/block.schema'; import { ParagraphBlockDocument } from 'src/block/schemas/blocks/paragraph.schema'; import { CodeBlockDocument } from 'src/block/schemas/blocks/code.schema';
Mabloq/mabloq-notion
app/src/block/dto/extra-models/base-block.dto.ts
<reponame>Mabloq/mabloq-notion<filename>app/src/block/dto/extra-models/base-block.dto.ts import { ApiProperty } from '@nestjs/swagger'; import { BlockEnum } from '../../../block/schemas/common/block-enum'; export class BaseBlockDto { object: 'block'; @ApiProperty({ enum: BlockEnum }) type: string; }
Mabloq/mabloq-notion
app/src/block/interfaces/blocks/file.interface.ts
import { BaseBlockInterface } from '../block.interface'; import { FileObjectInterface } from '../common/file-object.interface'; export interface FileBlockInterface extends BaseBlockInterface { file: FileObjectInterface; }
Mabloq/mabloq-notion
app/src/block/dto/extra-models/properties/property-types/number-property.dto.ts
<reponame>Mabloq/mabloq-notion import { ApiExtraModels, ApiProperty } from '@nestjs/swagger'; import { NumberPropertyInterface } from 'src/block/interfaces/properties/property-types/number-property.interface'; @ApiExtraModels() export class NumberPropertyDto implements NumberPropertyInterface { @ApiProperty({ default: 'number' }) type: 'number'; @ApiProperty() number: number; }
Mabloq/mabloq-notion
app/src/app.module.ts
<gh_stars>0 import { MiddlewareConsumer, Module, NestModule, RequestMethod, } from '@nestjs/common'; import { LoggerMiddleware } from './common/middleware/logger.middleware'; import { BlockController } from './block/controllers/block.controller'; import { BlockModule } from './block/block.module'; import { MongooseModule } from '@nestjs/mongoose'; @Module({ imports: [BlockModule, MongooseModule.forRoot(process.env.MONGO_URI)], }) export class AppModule implements NestModule { configure(consumer: MiddlewareConsumer) { consumer.apply(LoggerMiddleware).forRoutes('blocks'); consumer .apply(LoggerMiddleware) .forRoutes({ path: 'blocks', method: RequestMethod.GET }); consumer .apply(LoggerMiddleware) .exclude( { path: 'blocks', method: RequestMethod.GET }, { path: 'blocks', method: RequestMethod.POST }, 'blocks/(.*)', ) .forRoutes(BlockController); } }
Mabloq/mabloq-notion
app/src/block/schemas/properties/property.schema.ts
import { Prop, Schema, SchemaFactory } from '@nestjs/mongoose'; import { PropertyTypeEnum } from './property-type.enum'; import { Document, Schema as MongooseSchema } from 'mongoose'; import { randomIdGenerator } from 'src/block/utils/random-id-generator'; export type PropertyDocument = Property & Document; @Schema({ _id: false, discriminatorKey: 'type' }) export class Property { @Prop({ default: () => randomIdGenerator(4) }) id: string; @Prop({ type: String, required: true, enum: Object.values(PropertyTypeEnum), message: '{VALUE} is not supported', }) type!: string; } const PropertySchema = SchemaFactory.createForClass(Property); export { PropertySchema };
Mabloq/mabloq-notion
app/src/block/schemas/properties/property-types/rich-text-property.schema.ts
<filename>app/src/block/schemas/properties/property-types/rich-text-property.schema.ts import { Prop, Schema, SchemaFactory } from '@nestjs/mongoose'; import { Document } from 'mongoose'; import { RichTextSchema, RichText } from '../../common/rich-text.schema'; @Schema() export class RichTextProperty { @Prop({ _id: false, type: [RichTextSchema] }) rich_text: RichText[]; } export const RichTextPropertySchema = SchemaFactory.createForClass(RichTextProperty); export type TitlePropertyDocument = RichTextProperty & Document;
Mabloq/mabloq-notion
app/src/block/interfaces/blocks/paragraph.interface.ts
<gh_stars>0 import { BaseBlockInterface, BlockInterface } from '../block.interface'; import { RichTextInterface } from '../common/rich-text.interface'; export interface ParagraphInterface { color?: string; rich_text: RichTextInterface[]; children?: BlockInterface[]; } export interface ParagraphBlockInterface extends BaseBlockInterface { paragraph: ParagraphInterface; }
Mabloq/mabloq-notion
app/src/block/dto/extra-models/blocks/paragraph.dto.ts
import { ApiProperty, ApiExtraModels, getSchemaPath } from '@nestjs/swagger'; import { RichTextDto } from '../common/rich-text.dto'; import { BaseBlockDto } from '../base-block.dto'; import { BlockModelRefs, BlockDTOs } from '../block-models'; @ApiExtraModels(RichTextDto) export class ParagraphDto { @ApiProperty({ required: false }) color?: string; @ApiProperty({ type: 'array', items: { $ref: getSchemaPath(RichTextDto) }, required: true, }) rich_text: RichTextDto[]; @ApiProperty({ type: 'array', items: { anyOf: BlockModelRefs, }, required: false, }) children?: BlockDTOs[]; } @ApiExtraModels(ParagraphDto) export class ParagraphBlockDto extends BaseBlockDto { @ApiProperty({ type: 'object', items: { $ref: getSchemaPath(ParagraphDto) }, }) paragraph: ParagraphDto; }
Mabloq/mabloq-notion
app/src/block/dto/page/create-page.dto.ts
import { ApiProperty, getSchemaPath } from '@nestjs/swagger'; import { FileObjectInterface } from 'src/block/interfaces/common/file-object.interface'; import { FileObjectDto } from '../extra-models/common/file-object.dto'; import { RichTextDto } from '../extra-models/common/rich-text.dto'; import { PropertyInterface } from 'src/block/interfaces/properties/property.interface'; import { NumberPropertyDto } from '../extra-models/properties/property-types/number-property.dto'; import { SelectPropertyDto } from '../extra-models/properties/property-types/select-property.dto'; import { TitlePropertyDto } from '../extra-models/properties/property-types/title-property.dto'; import { PageInterface } from 'src/block/interfaces/page.interface'; import { ParagraphBlockDto } from '../extra-models/blocks/paragraph.dto'; import { CodeBlockDto } from '../extra-models/blocks/code.dto'; import { Heading1BlockDto } from '../extra-models/blocks/heading1.dto'; import { ImageBlockDto } from '../extra-models/blocks/image.dto'; import { BlockDTOs, BlockModelRefs } from '../extra-models/block-models'; import { ParentInerface } from 'src/block/interfaces/common/parent.interface'; import { DatabaseParentDto } from '../extra-models/parents/database-parent.dto'; import { PageParentDto } from '../extra-models/parents/page-parent.dto'; export class CreatePageDto implements Omit<PageInterface, 'id' | 'content'> { @ApiProperty({ required: true }) object: string; @ApiProperty() parent_id?: string; @ApiProperty({ type: 'object', anyOf: [ { $ref: getSchemaPath(DatabaseParentDto) }, { $ref: getSchemaPath(PageParentDto) }, ], }) parent?: ParentInerface; @ApiProperty({ items: { $ref: getSchemaPath(FileObjectDto) } }) cover?: FileObjectInterface; @ApiProperty({ items: { $ref: getSchemaPath(FileObjectDto) } }) icon?: FileObjectInterface; @ApiProperty({ type: Boolean }) archived?: boolean; @ApiProperty() created_by: string; @ApiProperty() created_time: string; @ApiProperty() last_edited_by: string; @ApiProperty() last_edited_time: string; @ApiProperty({ type: 'array', items: { $ref: getSchemaPath(RichTextDto), }, required: true, }) @ApiProperty({ type: 'object', additionalProperties: { anyOf: [ { $ref: getSchemaPath(RichTextDto) }, { $ref: getSchemaPath(NumberPropertyDto) }, { $ref: getSchemaPath(SelectPropertyDto) }, { $ref: getSchemaPath(TitlePropertyDto) }, ], }, }) properties: { [key: string | symbol]: PropertyInterface; title: PropertyInterface; }; @ApiProperty({ default: true }) has_content: boolean; @ApiProperty({ type: 'array', items: { anyOf: BlockModelRefs, }, }) content?: BlockDTOs[]; }
Mabloq/mabloq-notion
app/src/block/interfaces/common/rich-text.interface.ts
import { AnnotationInterface } from './annotation.interface'; import { TextInterface } from './text.interface'; export interface RichTextInterface { plain_text: string; href?: string; type: string; text: TextInterface; annotation?: AnnotationInterface; }
Mabloq/mabloq-notion
app/src/block/interfaces/properties/property-types/title-property.interface.ts
<reponame>Mabloq/mabloq-notion import { RichTextInterface } from '../../common/rich-text.interface'; import { BasePropertyInterface } from '../property.interface'; export interface TitlePropertyInterface { type: 'title'; title: RichTextInterface[]; }
Mabloq/mabloq-notion
app/src/block/interfaces/properties/property-types/multi-select-property.interface.ts
export interface MultiSelectPropertyInterface { type: 'multi_select'; multi_select: Array<{ name: string }>; }
Mabloq/mabloq-notion
app/src/block/interfaces/block.interface.ts
import { ParagraphBlockInterface } from './blocks/paragraph.interface'; import { Heading1Interface } from './blocks/heading1.interface'; import { CodeBlockInterface } from './blocks/code.interface'; import { FileBlockInterface } from './blocks/file.interface'; import { ImageBlockInterface } from './blocks/image.interface'; export interface BaseBlockInterface { id?: string; object: string; type: string; created_time: string; last_edited_time: string; updated_by: string; has_children: boolean; children?: string[]; } export type BlockInterface = | ParagraphBlockInterface | Heading1Interface | CodeBlockInterface | ImageBlockInterface | FileBlockInterface;
Mabloq/mabloq-notion
app/src/block/interfaces/properties/property-types/select-property.interface.ts
<reponame>Mabloq/mabloq-notion<filename>app/src/block/interfaces/properties/property-types/select-property.interface.ts export interface SelectPropertyInterface { type: 'select'; select: { name: string }; }
Mabloq/mabloq-notion
app/src/block/dto/extra-models/blocks/image.dto.ts
import { ApiProperty, ApiExtraModels, getSchemaPath } from '@nestjs/swagger'; import { FileObjectDto } from '../common/file-object.dto'; import { BaseBlockDto } from '../base-block.dto'; import { FileObjectInterface } from 'src/block/interfaces/common/file-object.interface'; @ApiExtraModels(FileObjectDto) export class ImageDto implements FileObjectInterface { @ApiProperty({ default: 'external' }) type: string; @ApiProperty({ required: true, }) url: string; } @ApiExtraModels(ImageDto) export class ImageBlockDto extends BaseBlockDto { @ApiProperty({ type: 'object', items: { $ref: getSchemaPath(ImageDto) }, }) image: ImageDto; }
Mabloq/mabloq-notion
app/src/block/schemas/common/object-enum.ts
export enum ObjectEnum { BLOCK = 'block', PAGE = 'page', DATABASE = 'database', USER = 'user', } export type ObjectType = | ObjectEnum.BLOCK | ObjectEnum.PAGE | ObjectEnum.DATABASE | ObjectEnum.USER;
Mabloq/mabloq-notion
app/src/block/interfaces/index.ts
<reponame>Mabloq/mabloq-notion import { ParagraphInterface, ParagraphBlockInterface, } from './blocks/paragraph.interface'; import { Heading1Interface, Heading1BlockInterface, } from './blocks/heading1.interface'; import { CodeInterface, CodeBlockInterface } from './blocks/code.interface'; import { BaseBlockInterface, BlockInterface } from './block.interface'; export { BlockInterface, BaseBlockInterface, ParagraphInterface, ParagraphBlockInterface, Heading1Interface, Heading1BlockInterface, CodeInterface, CodeBlockInterface, };
Mabloq/mabloq-notion
app/src/block/services/page.service.ts
import { Injectable } from '@nestjs/common'; import { CreateDatabaseDto } from '../dto/database/create-database.dto'; import { Model, FilterQuery } from 'mongoose'; import { InjectModel } from '@nestjs/mongoose'; import { HigherOrderBlock } from '../schemas/higher-order-block.schema'; import { CreatePageDto } from '../dto/page/create-page.dto'; import { Block } from '../schemas/block.schema'; import { DatabaseDocument } from '../schemas/database.schema'; import { isDatabaseParent, isPageParent, } from '../utils/type-guards/parent-types'; import { PropertiesConfigInterface, PropertiesInterface, PropertyConfigInterface, } from '../interfaces/properties/property.interface'; import { DatabaseService } from './database.service'; import PageParentValidator from '../utils/page-validators/validators/page-parent-validator'; import DatabaseParentValidator from '../utils/page-validators/validators/database-parent-validator'; @Injectable() export class PageService { constructor( @InjectModel(HigherOrderBlock.name) private higherOrderBlockModel: Model<HigherOrderBlock>, private dataBaseService: DatabaseService, ) {} private onlyTitleProperties(properties: PropertiesInterface) { const fieldValues = Object.keys(properties); return fieldValues.length == 1 && fieldValues[0] == 'title'; } private onlyDatabaseProperties( pageProperites: PropertiesInterface, DatabaseProperties: PropertiesConfigInterface, ) { const pagePropertyeKeys = Object.keys(pageProperites); const databasePropertyKeys = Object.keys(DatabaseProperties); return pagePropertyeKeys.every((key) => databasePropertyKeys.includes(key)); } async insertOne(createPageDto: CreatePageDto): Promise<HigherOrderBlock> { if (isPageParent(createPageDto.parent)) { const validator = new PageParentValidator(createPageDto); await validator.validate(); } else if (isDatabaseParent(createPageDto.parent)) { const parentId = createPageDto.parent.database_id; const database = await this.dataBaseService.findOne(parentId); const dbParentValidator = new DatabaseParentValidator(createPageDto); await dbParentValidator.validate(database.properties); } //check if CreatePageDto has blocks children //If has block children, create all of othem and map results to array of ObjectIds and add them to Page const createdBlock = await this.higherOrderBlockModel.create(createPageDto); return createdBlock.save(); } async findChildren(parentId: string) { const findQuery: FilterQuery<HigherOrderBlock> = { parent_id: parentId, }; const fetchedBlocks = await this.higherOrderBlockModel .find(findQuery) .exec(); return fetchedBlocks; } async findOne(id: string) { return await this.higherOrderBlockModel.findById(id); } // async findDatabasePages() }
Mabloq/mabloq-notion
app/src/block/schemas/parents/parent.schema.ts
import { Prop, Schema, SchemaFactory } from '@nestjs/mongoose'; export enum ParentEnum { DATABASE_ID = 'database_id', PAGE_ID = 'page_id', } @Schema({ _id: false, discriminatorKey: 'type' }) export class Parent { @Prop({ type: String, enum: Object.values(ParentEnum), required: true }) type!: string; } export const ParentSchema = SchemaFactory.createForClass(Parent);
Mabloq/mabloq-notion
app/src/block/dto/extra-models/block-models.ts
<gh_stars>0 import { CodeBlockDto } from './blocks/code.dto'; import { ParagraphBlockDto } from './blocks/paragraph.dto'; import { Heading1BlockDto } from './blocks/heading1.dto'; import { ReferenceObject } from '@nestjs/swagger/dist/interfaces/open-api-spec.interface'; import { getSchemaPath } from '@nestjs/swagger'; import { ImageBlockDto } from './blocks/image.dto'; export type BlockDTOs = | CodeBlockDto | ParagraphBlockDto | Heading1BlockDto | ImageBlockDto; export const BlockModelRefs: ReferenceObject[] = [ { $ref: getSchemaPath(CodeBlockDto) }, { $ref: getSchemaPath(ParagraphBlockDto) }, { $ref: getSchemaPath(Heading1BlockDto) }, { $ref: getSchemaPath(ImageBlockDto) }, ];
Mabloq/mabloq-notion
app/src/block/utils/page-validators/create-page-validator.ts
<filename>app/src/block/utils/page-validators/create-page-validator.ts import { CreatePageDto } from 'src/block/dto/page/create-page.dto'; import { isDatabaseParent, isPageParent } from '../type-guards/parent-types'; import IPageValidator from './page-validator-interface'; import DatabaseParentValidator from './validators/database-parent-validator'; import PageParentValidator from './validators/page-parent-validator'; export default function createPageValidator( createPageDto: CreatePageDto, ): IPageValidator { if (isPageParent(createPageDto.parent)) { return new PageParentValidator(createPageDto); } else if (isDatabaseParent(createPageDto.parent)) { return new DatabaseParentValidator(createPageDto); } }
Mabloq/mabloq-notion
app/src/block/schemas/database.schema.ts
<reponame>Mabloq/mabloq-notion import { Prop, Schema, SchemaFactory } from '@nestjs/mongoose'; import { Document } from 'mongoose'; import { PropertySchema } from './properties/property.schema'; import { DatabaseInterface } from '../interfaces/database.interface'; import { FileObjectInterface } from '../interfaces/common/file-object.interface'; import { PropertyConfigInterface } from '../interfaces/properties/property.interface'; import { ParentInerface } from '../interfaces/common/parent.interface'; import { PropertyTypeEnum } from './properties/property-type.enum'; import { TitlePropertySchema } from './properties/property-types/title-property.schema'; import { NumberPropertySchema } from './properties/property-types/number-property.schema'; import { RichTextPropertySchema } from './properties/property-types/rich-text-property.schema'; import { SelectPropertySchema } from './properties/property-types/select-property.schema'; import { MultiSelectPropertySchema } from './properties/property-types/multi-select-property.schema'; import { SelectConfigSchema } from './properties/property-config/select-config-schema'; import { NumberConfigSchema } from './properties/property-config/number-config-schema'; @Schema({ _id: false }) export class Database implements DatabaseInterface { object!: string; archived: boolean; icon: FileObjectInterface; cover: FileObjectInterface; parent: ParentInerface; parent_id: string; created_time: string; created_by: string; //TODO: Partial<User> last_edited_time: string; last_edited_by: string; //TODO: Partial<User> @Prop({ type: Map, of: PropertySchema, discriminators: [ { name: PropertyTypeEnum.RICH_TEXT, schema: RichTextPropertySchema }, { name: PropertyTypeEnum.SELECT, schema: SelectConfigSchema }, { name: PropertyTypeEnum.NUMBER, schema: NumberConfigSchema }, { name: PropertyTypeEnum.TITLE, schema: TitlePropertySchema }, ], }) properties: { title: PropertyConfigInterface; [key: string | symbol]: PropertyConfigInterface; }; } export type DatabaseDocument = Database & Document; export const DatabaseSchema = SchemaFactory.createForClass(Database);
Mabloq/mabloq-notion
app/src/block/tests/services/page.service.spec.ts
import { Test, TestingModule } from '@nestjs/testing'; import { PageService } from '../../services/page.service'; import { getModelToken } from '@nestjs/mongoose'; import { Query, Model } from 'mongoose'; import { Block, BlockDocument } from '../../schemas/block.schema'; import { CreateBlockDto } from '../../dto/create-block.dto'; import { BlockDTOs } from '../../dto/extra-models/block-models'; import { mockPage, mockPageDocument, mockCreatePageDto } from '../mocks/page'; import { HigherOrderBlockDocument, HigherOrderBlock, } from '../../schemas/higher-order-block.schema'; import { DatabaseService } from '../../services/database.service'; import { mockDatabase, mockDatabaseDocument } from '../mocks/database'; describe('PageService', () => { let pageService: PageService; let databaseService: DatabaseService; let higherOrderBlockModel: Model<HigherOrderBlock>; let blockModel: Model<Block>; beforeEach(async () => { const module: TestingModule = await Test.createTestingModule({ providers: [ PageService, DatabaseService, { provide: getModelToken('HigherOrderBlock'), useValue: { new: jest.fn(), constructor: jest.fn(), find: jest.fn(), findOne: jest.fn(), update: jest.fn(), create: jest.fn(), remove: jest.fn(), save: jest.fn(), exec: jest.fn(), }, }, { provide: getModelToken('Block'), useValue: { new: jest.fn(), constructor: jest.fn(), exec: jest.fn(), }, }, ], }).compile(); pageService = module.get<PageService>(PageService); databaseService = module.get<DatabaseService>(DatabaseService); higherOrderBlockModel = module.get<Model<HigherOrderBlock>>( getModelToken('HigherOrderBlock'), ); blockModel = module.get<Model<Block>>(getModelToken('Block')); }); it('should be defined', () => { expect(pageService).toBeDefined(); }); describe('insertOne', () => { it('throws error if parent is not database, and user tries to create page with properites other than title property', async () => { const pageDto = mockCreatePageDto('id-hello', 'Hello World', { title: { type: 'title', title: [ { type: 'text', plain_text: '<NAME>', text: { text: 'Hello World' }, }, ], }, invalid_field: { type: 'number', number: 5, }, }); await expect(async () => { await pageService.insertOne(pageDto); }).rejects.toThrow( 'Invalid Field Exception: Pages with parents of type page can only use title property', ); }); it('throws error if not given valid properties of parent database', async () => { const databaseInterface = mockDatabase(); jest .spyOn(databaseService, 'findOne') .mockImplementation(async () => mockDatabaseDocument(databaseInterface), ); const pageDto = mockCreatePageDto( 'id-hello', 'Hello World', { title: { type: 'title', title: [ { type: 'text', plain_text: 'Hello World', text: { text: 'Hello World' }, }, ], }, invalid_field: { type: 'number', number: 5, }, }, { database_id: 'database-id', type: 'database' }, ); await expect(async () => { await pageService.insertOne(pageDto); }).rejects.toThrow( 'Invalid Field exception: {invalid_field} not valid field(s) on database: {title, valid_field}', ); }); // it('If failes creating block children, if something goes wrong throw exception', async () => {}); }); afterEach(() => { jest.clearAllMocks(); }); });
Mabloq/mabloq-notion
app/src/block/schemas/blocks/code.schema.ts
<filename>app/src/block/schemas/blocks/code.schema.ts import { Prop, Schema, SchemaFactory } from '@nestjs/mongoose'; import { Document } from 'mongoose'; import { RichTextSchema } from '../common/rich-text.schema'; import { CodeBlockInterface, CodeInterface } from 'src/block/interfaces'; import { RichTextInterface } from 'src/block/interfaces/common/rich-text.interface'; export type CodeDocument = Code & Document; export type CodeBlockDocument = CodeBlock & Document; @Schema({ _id: false }) export class Code implements CodeInterface { @Prop() language: string; @Prop({ _id: false, type: [RichTextSchema] }) rich_text: RichTextInterface[]; } const CodeSchema = SchemaFactory.createForClass(Code); @Schema({ _id: false }) export class CodeBlock implements CodeBlockInterface { object: string; type: string; updated_by: string; created_time: string; last_edited_time: string; has_children: boolean; @Prop({ type: CodeSchema, required: true }) code: CodeInterface; } export const CodeBlockSchema = SchemaFactory.createForClass(CodeBlock);
Mabloq/mabloq-notion
app/src/block/dto/extra-models/properties/property-config/select-config-interface.dto.ts
<reponame>Mabloq/mabloq-notion import { ApiExtraModels } from '@nestjs/swagger'; import { SelectConfigInterface, SelectOptionInterface, } from 'src/block/interfaces/properties/property-config/select-config.interface'; @ApiExtraModels() export class SelectOptionDto implements Pick<SelectOptionInterface, 'color' | 'name'> { color: string; name: string; } @ApiExtraModels() export class SelectConfigDto implements SelectConfigInterface { options: SelectOptionInterface[]; }
Mabloq/mabloq-notion
app/src/block/schemas/parents/database-parent.schema.ts
<reponame>Mabloq/mabloq-notion<filename>app/src/block/schemas/parents/database-parent.schema.ts import { Prop, Schema, SchemaFactory } from '@nestjs/mongoose'; @Schema({ _id: false }) export class DatabaseParent { @Prop() database_id: string; } export const DatabaseParentSchema = SchemaFactory.createForClass(DatabaseParent);