repo_name
stringlengths 5
122
| path
stringlengths 3
232
| text
stringlengths 6
1.05M
|
|---|---|---|
SimonAlling/better-sweclockers
|
src/operations/uninteresting-subforums.ts
|
<filename>src/operations/uninteresting-subforums.ts<gh_stars>10-100
import * as CONFIG from "~src/config";
import * as SITE from "~src/site";
import * as T from "~src/text";
export default (uninterestingIDs: readonly number[]) => (e: {
body: HTMLElement,
}) => {
const rows = e.body.querySelectorAll<HTMLTableRowElement>("tr.forumThread");
for (const row of rows) {
const forumLink = row.querySelector<HTMLAnchorElement>("a.forum");
if (forumLink === null) {
return `Could not find forum link.`;
}
const match = forumLink.href.match(SITE.PATH.FORUM_CATEGORY);
if (match === null) {
return `Could not extract forum ID from this link: ${forumLink.outerHTML}`;
}
const id = parseInt(match[1]);
if (uninterestingIDs.includes(id)) {
row.classList.add(CONFIG.CLASS.uninteresting);
row.title = T.general.uninteresting_subforum(forumLink.textContent as string);
}
}
};
|
SimonAlling/better-sweclockers
|
src/operations/actions/replace-spaces-with-nbsps.ts
|
<reponame>SimonAlling/better-sweclockers
import * as CONFIG from "~src/config";
import * as T from "~src/text";
import { insertIn, selectedTextIn } from "../logic/textarea";
const SPACE = / /g;
const CONSECUTIVE_SPACES = / +/g;
export default function(textarea: HTMLTextAreaElement, undoSupport: boolean) {
const selectedText = selectedTextIn(textarea);
let n: false | number; // Lets us short-circuit with undo support.
if (undoSupport || (n = confirmationNeeded(selectedText), n === false) || confirm(T.general.nbsps_confirm(n))) { // `confirm` is problematic in Chrome (see docs/dialogs.md), but Chrome has full undo support.
insertIn(textarea, {
string: selectedText.replace(SPACE, CONFIG.NBSP),
replace: true,
});
}
}
// A heuristic intended to catch cases when the user likely didn't mean to replace spaces with NBSPs and/or it would be cumbersome to restore the change without undo support.
function confirmationNeeded(selectedText: string): false | number {
const numberOfSelectedSpaces = selectedText.match(SPACE)?.length || 0;
const numberOfSelectedSpaceSegments = selectedText.match(CONSECUTIVE_SPACES)?.length || 0;
// Replacing a large number of spread-out spaces with NBSPs is both uncommon and time-consuming to restore.
const confirmationNeeded = numberOfSelectedSpaces > 10 && numberOfSelectedSpaceSegments > 3;
return confirmationNeeded ? numberOfSelectedSpaces : false;
}
|
SimonAlling/better-sweclockers
|
src/operations/editing-tools.tsx
|
import { compose } from "@typed/compose";
import classNames from "classnames";
import { h, JSX } from "preact";
import * as CONFIG from "~src/config";
import { insertAfter, insertBefore, renderIn } from "~src/operations/logic/render";
import { P, Preferences } from "~src/preferences";
import { Position } from "~src/preferences/editing-tools";
import * as SITE from "~src/site";
import * as T from "~src/text";
import { BUTTON, BUTTONS, Button, COLORS, colorButton, insertButton, smileyButton, tagButton } from "./logic/editing-tools";
import { SMILEYS } from "./logic/smileys";
export default (undoSupport: boolean) => (e: { textarea: HTMLElement }) => {
const textarea = e.textarea;
const position = Preferences.get(P.editing_tools._.position);
const insertBeforeOrAfter = position === Position.ABOVE ? insertBefore : insertAfter;
const textareaParent = textarea.parentElement as HTMLElement;
renderIn(textareaParent, insertBeforeOrAfter(textarea), (
<EditingTools textarea={textarea as HTMLTextAreaElement} config={getEditingToolsConfig()} undoSupport={undoSupport} />
));
};
interface EditingToolsConfig {
special_characters: boolean
meta: boolean
code: boolean
math: boolean
whitespace: boolean
definitions: boolean
embed: boolean
doge: boolean
color_palette: boolean
smileys: boolean
}
// Needs to be a function because it's used "live" in the preferences menu:
export function getEditingToolsConfig(): EditingToolsConfig {
return {
special_characters: Preferences.get(P.editing_tools._.special_characters),
meta: Preferences.get(P.editing_tools._.meta),
code: Preferences.get(P.editing_tools._.code),
math: Preferences.get(P.editing_tools._.math),
whitespace: Preferences.get(P.editing_tools._.whitespace),
definitions: Preferences.get(P.editing_tools._.definitions),
embed: Preferences.get(P.editing_tools._.embed),
doge: Preferences.get(P.editing_tools._.doge),
color_palette: Preferences.get(P.editing_tools._.color_palette),
smileys: Preferences.get(P.editing_tools._.smileys),
} as const;
}
export function EditingTools(props: {
textarea: HTMLTextAreaElement,
disabled?: boolean,
config: EditingToolsConfig,
undoSupport: boolean,
}): JSX.Element {
// A "connected" button has been connected to the textarea.
const connected = (b: Button) => b(props.textarea, props.undoSupport);
const connectedTagButton = compose(connected, tagButton);
const connectedInsertButton = compose(connected, insertButton);
const connectedColorButton = compose(connected, colorButton);
const connectedSmileyButton = compose(connected, smileyButton);
return (
<div id={CONFIG.ID.editingTools} class={classNames(
CONFIG.CLASS.editingTools,
{ [CONFIG.CLASS.disabled]: props.disabled },
SITE.CLASS.bbcode, // so we can easily mimic forum post styles in our buttons
)}>
{props.config.special_characters ? (
<fieldset>
{T.special_characters.map(connectedInsertButton)}
</fieldset>
) : null}
{connectedTagButton({ tag: SITE.TAG.size, label: T.editing_tools.size_label, tooltip: T.editing_tools.size_tooltip, parameterized: true })}
{connectedTagButton({ tag: SITE.TAG.color, parameterized: true, tooltip: T.editing_tools.color_tooltip, class: CONFIG.CLASS.button_color })}
{connectedTagButton({ tag: SITE.TAG.font, tooltip: T.editing_tools.font_tooltip, parameterized: true })}
{connectedTagButton({ tag: SITE.TAG.mark, label: T.editing_tools.mark_label, tooltip: T.editing_tools.mark_tooltip })}
{connectedTagButton({ tag: SITE.TAG.abbr, label: T.editing_tools.abbr_label, parameterized: true, tooltip: T.editing_tools.abbr_tooltip })}
{connected(BUTTON.quote)}
{connected(BUTTON.splitQuote)}
{connectedTagButton({ tag: SITE.TAG.bq, label: "", tooltip: T.editing_tools.bq_tooltip, block: true, icon: { type: "RAW", image: CONFIG.ICONS.BLOCKQUOTE }, class: CONFIG.CLASS.button_blockquote })}
{connected(BUTTON.expander)}
{connectedTagButton({ tag: SITE.TAG.spoiler, tooltip: T.editing_tools.spoiler_tooltip, block: true, class: CONFIG.CLASS.button_spoiler })}
{connectedInsertButton({ insert: CONFIG.CONTENT.edit, tooltip: T.editing_tools.edit_tooltip, label: T.editing_tools.edit_label })}
{props.config.meta ? BUTTONS.meta.map(connected) : []}
{props.config.code ? BUTTONS.code.map(connected) : []}
{props.config.math ? BUTTONS.math.map(connected) : []}
{props.config.whitespace ? BUTTONS.whitespace.map(connected) : []}
{props.config.definitions ? BUTTONS.definitions.map(connected) : []}
{props.config.embed ? BUTTONS.embed(Preferences.get(P.editing_tools._.search_engine)).map(connected) : []}
{props.config.doge ? BUTTONS.doge.map(connected) : []}
{props.config.color_palette ? (
<fieldset class={CONFIG.CLASS.colorPalette}>
{COLORS.map(connectedColorButton)}
</fieldset>
) : null}
{props.config.smileys ? (
<fieldset class={CONFIG.CLASS.smileys}>
{SMILEYS.map(connectedSmileyButton)}
</fieldset>
) : null}
</div>
);
}
|
SimonAlling/better-sweclockers
|
src/operations/preferences-link.tsx
|
import { h } from "preact";
import * as CONFIG from "~src/config";
import { insertAtTheEnd, renderIn } from "~src/operations/logic/render";
import * as SITE from "~src/site";
import * as T from "~src/text";
export default (e: { settingsNavigation: HTMLElement }) => {
renderIn(e.settingsNavigation, insertAtTheEnd, (
<li title={T.general.preferences_link} class={SITE.CLASS.menuItem}>
<a href={CONFIG.PATH.PREFERENCES.link(SITE.PATH.SETTINGS.link)} class={SITE.CLASS.link}>
<span class={SITE.CLASS.icon}></span>
{" "} {/* SweClockers relies on whitespace for spacing here. */}
<span class={SITE.CLASS.label}>{T.general.preferences_link}</span>
</a>
</li>
));
};
|
SimonAlling/better-sweclockers
|
__tests__/preferences.test.ts
|
<reponame>SimonAlling/better-sweclockers
import insertPreferencesMenu from "../src/operations/preferences-menu";
describe("preferences menu", () => {
it("does not throw", () => {
window.fetch = mockFetch(""); // This means interests won't be populated, but we're not testing that here.
expect(insertPreferencesMenu).not.toThrow();
});
});
function mockFetch(data: string) {
return jest.fn().mockImplementation(() =>
Promise.resolve({
ok: true,
text: () => data,
})
);
}
|
SimonAlling/better-sweclockers
|
src/operations/remove-mobile-site-disclaimer.ts
|
<reponame>SimonAlling/better-sweclockers
import * as BB from "bbcode-tags";
import * as SITE from "~src/site";
const END_TAG_QUOTE = BB.end(SITE.TAG.quote);
const sentFrom = SITE.MOBILE_SITE_DISCLAIMER.sentFrom;
const mobileSiteDomain = SITE.MOBILE_SITE_DISCLAIMER.mobileSiteDomain;
const disclaimer = [
``,
`[size="smaller"]${sentFrom} [url="//${mobileSiteDomain}"]${mobileSiteDomain}[/url][/size]`,
END_TAG_QUOTE,
].join("\n");
export default (e: { textarea: HTMLElement }) => {
const textarea = e.textarea as HTMLTextAreaElement;
textarea.value = withoutDisclaimers(textarea.value);
};
// Removes all disclaimers recursively, so we can use a plain string for the replace pattern:
function withoutDisclaimers(text: string): string {
const withoutFirstDisclaimer = text.replace(disclaimer, END_TAG_QUOTE);
return text === withoutFirstDisclaimer ? text : withoutDisclaimers(withoutFirstDisclaimer);
}
|
SimonAlling/better-sweclockers
|
src/preferences/edit-mode.ts
|
import {
BooleanPreference,
IntegerRangePreference,
MultichoicePreference,
} from "ts-preferences";
import * as CONFIG from "~src/config";
import * as T from "~src/text";
const textarea_size_toggle = new BooleanPreference({
key: "textarea_size_toggle",
default: true,
label: T.preferences.edit_mode.textarea_size_toggle,
description: T.preferences.edit_mode.textarea_size_toggle_description,
extras: { class: [ CONFIG.CLASS.inlinePreference, CONFIG.CLASS.primaryInlinePreference ] },
});
const dependencies_textarea_size_toggle = [
{
preference: textarea_size_toggle,
condition: (v: boolean) => v,
},
];
const DEFAULT_TEXTAREA_SIZE = 360;
const SPACE = " ", TAB = "\t";
export default {
autosave_draft: new BooleanPreference({
key: "autosave_draft",
default: true,
label: T.preferences.edit_mode.autosave_draft,
description: T.preferences.edit_mode.autosave_draft_description,
}),
draft_mode_toggle: new BooleanPreference({
key: "draft_mode_toggle",
default: true,
label: T.preferences.edit_mode.draft_mode_toggle,
description: T.preferences.edit_mode.draft_mode_toggle_description,
}),
textarea_size: new IntegerRangePreference({
key: "textarea_size",
default: DEFAULT_TEXTAREA_SIZE,
min: 0, max: Number.MAX_VALUE,
label: T.preferences._.NO_LABEL,
extras: { implicit: true },
}),
textarea_size_toggle,
textarea_size_small: new IntegerRangePreference({
key: "textarea_size_small",
default: 250,
min: 50, max: 2000,
label: T.preferences.edit_mode.textarea_size_small,
description: T.preferences.edit_mode.textarea_size_toggle_description,
dependencies: dependencies_textarea_size_toggle,
extras: { class: CONFIG.CLASS.inlinePreference },
}),
textarea_size_large: new IntegerRangePreference({
key: "textarea_size_large",
default: 750,
min: 50, max: 2000,
label: T.preferences.edit_mode.textarea_size_large,
description: T.preferences.edit_mode.textarea_size_toggle_description,
dependencies: dependencies_textarea_size_toggle,
extras: { class: CONFIG.CLASS.inlinePreference, suffix: T.preferences.edit_mode.textarea_size_unit },
}),
monospace_font: new BooleanPreference({
key: "monospace_font",
default: false,
label: T.preferences.edit_mode.monospace_font,
description: T.preferences.edit_mode.monospace_font_description,
extras: { class: [ CONFIG.CLASS.inlinePreference, CONFIG.CLASS.primaryInlinePreference ] },
}),
monospace_font_in_quick_reply_form: new BooleanPreference({
key: "monospace_font_in_quick_reply_form",
default: false,
label: T.preferences._.in_quick_reply_form,
description: T.preferences._.in_quick_reply_form_description,
extras: { class: CONFIG.CLASS.inlinePreference },
}),
improved_builtin_editing_tools: new BooleanPreference({
key: "improved_builtin_editing_tools",
default: true,
label: T.preferences.edit_mode.improved_builtin_editing_tools,
description: T.preferences.edit_mode.improved_builtin_editing_tools_description,
}),
insert_heading_toolbar_button: new BooleanPreference({
key: "insert_heading_toolbar_button",
default: true,
label: T.preferences.edit_mode.insert_heading_toolbar_button,
description: T.preferences.edit_mode.insert_heading_toolbar_button_description,
}),
insert_table_toolbar_button: new BooleanPreference({
key: "insert_table_toolbar_button",
default: true,
label: T.preferences.edit_mode.insert_table_toolbar_button,
description: T.preferences.edit_mode.insert_table_toolbar_button_description,
}),
keyboard_shortcuts: new BooleanPreference({
key: "keyboard_shortcuts",
default: false,
label: T.preferences.edit_mode.keyboard_shortcuts,
description: T.preferences.edit_mode.keyboard_shortcuts_description,
extras: { class: [ CONFIG.CLASS.inlinePreference, CONFIG.CLASS.primaryInlinePreference ] },
}),
keyboard_shortcuts_in_quick_reply: new BooleanPreference({
key: "keyboard_shortcuts_in_quick_reply",
default: false,
label: T.preferences._.in_quick_reply_form,
description: T.preferences._.in_quick_reply_form_description,
extras: { class: CONFIG.CLASS.inlinePreference },
}),
insert_tab: new BooleanPreference({
key: "insert_tab",
default: true,
label: T.preferences.edit_mode.insert_tab,
description: T.preferences.edit_mode.insert_tab_description,
extras: { class: [CONFIG.CLASS.inlinePreference, CONFIG.CLASS.primaryInlinePreference] },
}),
insert_tab_content: new MultichoicePreference({
key: "insert_tab_content",
default: TAB,
label: T.preferences._.NO_LABEL,
options: [
{
value: TAB,
label: T.preferences.edit_mode.insert_tab_tab as string, // Without the type assertion, too small a type is inferred.
},
].concat(
[ 2, 3, 4 ].map(n => ({
value: SPACE.repeat(n),
label: T.preferences.edit_mode.insert_tab_spaces(n),
}))
),
extras: { class: [CONFIG.CLASS.inlinePreference] },
}),
remember_caret_position: new BooleanPreference({
key: "remember_caret_position",
default: true,
label: T.preferences.edit_mode.remember_caret_position,
description: T.preferences.edit_mode.remember_caret_position_description,
}),
remove_mobile_site_disclaimer: new BooleanPreference({
key: "remove_mobile_site_disclaimer",
default: true,
label: T.preferences.edit_mode.remove_mobile_site_disclaimer,
description: T.preferences.edit_mode.remove_mobile_site_disclaimer_description,
}),
} as const;
|
SimonAlling/better-sweclockers
|
src/operations/draft-mode-toggle.ts
|
<filename>src/operations/draft-mode-toggle.ts
import * as Storage from "ts-storage";
import * as CONFIG from "~src/config";
import * as T from "~src/text";
export default (e: {
saveButton: HTMLElement,
previewButton: HTMLElement,
}) => {
const saveButton = e.saveButton as HTMLButtonElement; // Selector should ensure this.
const checkbox = document.createElement("input");
checkbox.type = "checkbox";
const label = document.createElement("label");
label.classList.add(CONFIG.CLASS.checkbox);
label.title = T.general.draft_mode_toggle_tooltip;
label.appendChild(checkbox);
const text = document.createTextNode(T.general.draft_mode_toggle_label);
label.appendChild(text);
const response = Storage.get_session(CONFIG.KEY.draft_mode, false);
if (![ Storage.Status.ABSENT, Storage.Status.OK ].includes(response.status)) {
return `Could not read draft mode state (error type: ${response.status}).`;
}
const draftModeEnabled = response.value;
checkbox.checked = draftModeEnabled;
checkbox.addEventListener("change", toggle(checkbox, saveButton));
(e.previewButton).insertAdjacentElement("afterend", label);
apply(draftModeEnabled, saveButton);
};
function toggle(checkbox: HTMLInputElement, saveButton: HTMLButtonElement): EventHandlerNonNull {
return _ => {
const draftModeEnabled = checkbox.checked;
Storage.set_session(CONFIG.KEY.draft_mode, draftModeEnabled);
apply(draftModeEnabled, saveButton);
};
}
function apply(draftModeEnabled: boolean, saveButton: HTMLButtonElement): void {
saveButton.disabled = draftModeEnabled;
saveButton.title = draftModeEnabled ? T.general.draft_mode_enabled_tooltip : "";
}
|
SimonAlling/better-sweclockers
|
src/operations/prevent-accidental-signout.ts
|
import SELECTOR from "~src/selectors";
import * as SITE from "~src/site";
import * as T from "~src/text";
export default () => { // We can't take the signout button as a dependency, because it only exists on the user's own profile page.
const ourUserID = SITE.getUserID();
if (ourUserID === undefined) {
return `Could not extract current user's ID.`;
}
const isNotLoggedIn = ourUserID === SITE.USER_ID_NOT_LOGGED_IN;
if (isNotLoggedIn) {
return;
}
const isOwnProfilePage = SITE.PATH.PROFILE(ourUserID).test(document.location.pathname);
if (!isOwnProfilePage) {
return;
}
const signoutButton = document.querySelector(SELECTOR.signoutButton);
if (signoutButton === null) {
return `Could not find signout button (${SELECTOR.signoutButton}).`;
}
signoutButton.addEventListener("click", event => {
if (!confirm(T.general.signout_confirmation)) {
event.preventDefault();
}
});
};
|
SimonAlling/better-sweclockers
|
src/operations/quote-signature-buttons.tsx
|
import * as BB from "bbcode-tags";
import classnames from "classnames";
import { Fragment, h, JSX } from "preact";
import { isNull, isString, only } from "ts-type-guards";
import { log } from "userscripter";
import * as CONFIG from "~src/config";
import { insertAtTheEnd, renderIn } from "~src/operations/logic/render";
import { P, Preferences } from "~src/preferences";
import SELECTOR from "~src/selectors";
import * as SITE from "~src/site";
import * as T from "~src/text";
const userMessage = Preferences.get(P.forum_threads._.quote_signature_message);
export default () => {
const csrf = session.getCsrfToken();
const forumPosts = document.getElementsByClassName(SITE.CLASS.forumPost);
for (const post of only(HTMLElement)(Array.from(forumPosts))) {
if (post.classList.contains(SITE.CLASS.forumPostByCurrentUser)) {
// We don't want buttons on the reader's own posts, because they can overflow when the edit button is visible.
continue;
}
const signature = post.querySelector("." + SITE.CLASS.forumPostSignature);
const controls = post.querySelector("." + SITE.CLASS.forumPostControls);
const authorName = post.querySelector(SELECTOR.forumPostAuthorLink)?.textContent?.trim();
const quoteURL = post.querySelector<HTMLAnchorElement>(SELECTOR.quoteButton)?.href;
if (controls === null) return couldNotExtractFromPost("controls", post.id);
if (!isString(authorName)) return couldNotExtractFromPost("author name", post.id);
if (!isString(quoteURL)) return couldNotExtractFromPost("quote URL", post.id);
renderIn(controls, insertAtTheEnd, button({
signature,
authorName,
userMessage,
quoteURL,
csrf,
}));
}
};
function button(props: {
signature: Element | null,
authorName: string,
userMessage: string,
quoteURL: string,
csrf: string,
}): JSX.Element {
const noSignature = isNull(props.signature);
return (
<button
class={classnames(CONFIG.CLASS.quoteSignatureButton, SITE.CLASS.button, noSignature ? SITE.CLASS.disabled : null)}
title={noSignature ? T.general.quote_signature_tooltip_no_signature(props.authorName) : T.general.quote_signature_tooltip}
disabled={noSignature}
onClick={() => {
fetch(props.quoteURL, { credentials: "same-origin" }) // https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/fetch#Parameters
.then(response => response.text())
.then(responseContent => {
const responseDocument = new DOMParser().parseFromString(responseContent, "text/html");
const quoteTextarea = responseDocument.querySelector("textarea");
if (quoteTextarea === null) {
throw couldNotExtract("textarea from fetch response");
}
const form = document.createElement("form");
form.hidden = true;
form.method = "POST";
form.action = props.quoteURL;
renderIn(form, insertAtTheEnd, (
<>
<input name={SITE.FORM.name.csrfToken} type="hidden" value={props.csrf} />
<input name={SITE.FORM.name.action} type="hidden" value={SITE.FORM.value.preview} />
<textarea name={SITE.FORM.name.message} hidden>
{withSignatureAndUserMessage({
rawQuote: quoteTextarea.textContent || "",
rawSignature: props.signature?.textContent || "",
userMessage: props.userMessage,
})}
</textarea>
</>
));
document.documentElement.appendChild(form); // Otherwise: "Form submission canceled because the form is not connected"
form.submit();
})
.catch(log.error);
}}
>
<span class={SITE.CLASS.label}>{T.general.quote_signature_label}</span>
</button>
);
}
function withSignatureAndUserMessage(x: {
rawQuote: string
rawSignature: string
userMessage: string
}): string {
const SIGNATURE_FONT_SIZE = "smaller";
const textToInsert = [
`\n`,
`________________________`,
`\n`,
BB.start(SITE.TAG.size, SIGNATURE_FONT_SIZE),
x.rawSignature.trim(),
BB.end(SITE.TAG.size),
].join("");
return x.rawQuote.replace(/\n*(?=\[\/quote\]\s*$)/, textToInsert) + x.userMessage;
}
function couldNotExtract(what: string): string {
return `Could not extract ${what}.`;
}
function couldNotExtractFromPost(what: string, htmlId: string): string {
return couldNotExtract(`${what} from post with id="${htmlId}"`);
}
declare namespace session {
function getCsrfToken(): string
}
|
SimonAlling/better-sweclockers
|
src/operations/improved-builtin-editing-tools-url.ts
|
import * as BB from "bbcode-tags";
import { lines, unlines } from "lines-unlines";
import { is } from "ts-type-guards";
import { log } from "userscripter";
import { insertIn, selectRangeIn, selectedTextIn } from "~src/operations/logic/textarea";
import SELECTOR from "~src/selectors";
import * as SITE from "~src/site";
import * as T from "~src/text";
declare namespace Beta { const Forms: any; }
declare namespace Taiga { const Strings: any; }
export default (undoSupport: boolean) => () => {
/*
This operation must run "early" (before DOMContentLoaded), because otherwise it can't override the default action for the URL button.
However, it should not run _too_ early, because it fails if SweClockers' script hasn't yet defined Beta.
I haven't managed to make this operation work at all in Firefox; the default action is just not overridden.
*/
try { // If SweClockers change their "API", we want to fail gracefully.
Beta.Forms.Toolbar.Buttons.HyperlinkButton.prototype.insertTemplate = () => {
const textarea = document.querySelector(SELECTOR.textarea);
if (!is(HTMLTextAreaElement)(textarea)) {
log.error(`Could not find textarea.`);
return;
}
const selectedText = selectedTextIn(textarea);
const selectedLines = lines(selectedText);
if (selectedLines.length > 1) {
// Multiline mode (closely resembling SweClockers' native behavior).
let n: false | number; // Lets us short-circuit with undo support.
if (undoSupport || (n = confirmationNeeded(selectedLines), n === false) || confirm(T.general.generic_lines_confirm(n))) {
const formattedLines = selectedLines.map(line => (
Taiga.Strings.sprintf(
BB.start(SITE.TAG.url) + "%s" + BB.end(SITE.TAG.url),
Taiga.Strings.trim(line),
)
));
insertIn(textarea, {
string: unlines(formattedLines),
replace: true,
});
}
} else {
const suggestedLinkUrl = isUrlLike(selectedText) ? selectedText : ""; // Same behavior as SweClockers.
const suggestedLinkText = selectedText;
const providedLinkUrl = prompt(T.general.improved_url_button_url, suggestedLinkUrl);
if (providedLinkUrl === null) {
return; // Canceling altogether if the user cancels the prompt feels intuitive.
}
const providedLinkText = prompt(T.general.improved_url_button_text, suggestedLinkText);
if (providedLinkText === null) {
return; // Canceling altogether if the user cancels the prompt feels intuitive.
}
const finalLinkUrl = providedLinkUrl;
const finalLinkText = providedLinkText === "" ? finalLinkUrl : providedLinkText;
const selectionStart = textarea.selectionStart; // Must be calculated before any modification is made.
const startTag = BB.start(SITE.TAG.url, finalLinkUrl);
// We _could_ just wrap if the final link text equals the selectedText text, but AFAICT it wouldn't give us any benefits versus inserting and then selecting.
insertIn(textarea, {
string: startTag + finalLinkText + BB.end(SITE.TAG.url),
replace: true, // Risk of accidental deletion is low because the user is given two prompts before anything is modified in the textarea.
});
const newSelectionStart = selectionStart + startTag.length;
const newSelectionEnd = newSelectionStart + finalLinkText.length;
selectRangeIn(textarea, newSelectionStart, newSelectionEnd);
}
};
} catch (err) {
return err.toString(); // String conversion is necessary for the error to be handled properly by Userscripter.
}
};
// A heuristic intended to catch cases when the user likely didn't mean to format links and/or it would be cumbersome to restore the change without undo support.
function confirmationNeeded(selectedLines: readonly string[]): false | number {
return (
selectedLines.length > 5 && !selectedLines.every(isUrlLike)
? selectedLines.length
: false
);
}
function isUrlLike(s: string): boolean {
// The regex is copied from SweClockers.
return /^([a-z]+:\/\/|www\.)/i.test(s);
}
|
SimonAlling/better-sweclockers
|
src/operations/replace-followed-threads-link.ts
|
import { is } from "ts-type-guards";
import * as SITE from "~src/site";
import * as T from "~src/text";
export default (e: { followedThreadsLinkTextOrSigninButton: HTMLElement }) => {
const notLoggedIn = is(HTMLAnchorElement)(e.followedThreadsLinkTextOrSigninButton);
if (notLoggedIn) return;
const text = e.followedThreadsLinkTextOrSigninButton;
const link = text.parentElement as HTMLAnchorElement;
text.textContent = T.general.my_posts;
link.href = SITE.PATH.MY_POSTS;
link.classList.remove(SITE.CLASS.colorOrange);
};
|
SimonAlling/better-sweclockers
|
src/lib/proofreading/classes.ts
|
<reponame>SimonAlling/better-sweclockers<filename>src/lib/proofreading/classes.ts
// This file cannot contain Webpack-resolved imports (e.g. "~src/foo").
export default {
proofread: "proofread",
any: "any",
mistake: "mistake",
verified: "verified",
} as const;
|
hqwlkj/umi-antd-mobile
|
config/config.ts
|
<reponame>hqwlkj/umi-antd-mobile<filename>config/config.ts<gh_stars>10-100
import { defineConfig } from "umi";
import routes from "./routes";
/**
* UMI 配置
* 更多相关配置查询 https://umijs.org/zh-CN/docs/config
*/
export default defineConfig({
layout: false,
title: "umi-antd-mobile",
dynamicImport: {
loading: "@/pages/loading"
},
routes: [...routes],
nodeModulesTransform: {
type: "none"
},
antdMobile: {
hd: true
},
alias: {
// "antd-mobile": "antd-mobile/2x" //使用高清适配
},
mfsu: { production: { output: ".mfsu-production" } },
fastRefresh: {},
extraBabelPlugins: [
// ["import", { "libraryName": "antd-mobile", "libraryDirectory": "es/components", "style": false}]
],
extraPostCSSPlugins: [
require("postcss-px-to-viewport")({
viewportWidth: 750,
mediaQuery: true
})
],
metas: [
{
name: "keywords",
content: "umi, umijs, antd-mobile"
},
{
name: "description",
content: "基于umi@3.x + antd-mobile@next 快速构建h5及app应用"
}
],
// https://mobile.ant.design/zh/guide/quick-start#%E5%85%BC%E5%AE%B9%E6%80%A7
targets:{
chrome: 49,
ios: 10
}
});
|
hqwlkj/umi-antd-mobile
|
src/authority/index.tsx
|
import { ReactChild, ReactFragment, ReactPortal, useCallback } from 'react';
import { Redirect } from 'umi'
//假的权限验证
const useAuth = ()=>{
const isLogin = true;
return {isLogin}
}
export default (props: { children: boolean | ReactChild | ReactFragment | ReactPortal | null | undefined; }) => {
const { isLogin } = useAuth();
if (isLogin) {
return <div>{ props.children }</div>;
} else {
return <Redirect to="/login" />;
}
}
|
hqwlkj/umi-antd-mobile
|
src/pages/details/index.tsx
|
<reponame>hqwlkj/umi-antd-mobile
import { NavBar, Toast, Result, Space, ProgressCircle } from 'antd-mobile';
import { useHistory } from 'umi';
import { useContext } from 'react';
import { TabBarContext } from '@/layouts';
export default () => {
const history = useHistory();
const todo = useContext(TabBarContext);
const back = () =>
Toast.show({
content: '点击了返回区域',
duration: 1000,
afterClose: () => history.goBack(),
});
return (
<div>
<NavBar back="返回" onBack={back}>
详情页面
</NavBar>
<Result
status="success"
title="操作成功"
description="内容详情可折行,建议不超过两行建议不超过两行建议不超过两行"
/>
<Space justify={'center'} block style={{ '--gap': '24px' }}>
<div style={{ fontSize: 22 }}>
待办数:{todo.items.todoBadge || '0'}
</div>
<div style={{ fontSize: 22 }}>
消息数:{todo.items.messageBadge || '0'}
</div>
</Space>
<br />
<br />
<br />
<br />
<div>
<div className="">指定线条宽度</div>
<Space style={{ '--gap': '24px' }}>
<ProgressCircle percent={75} style={{ '--track-width': '2px' }}>
75%
</ProgressCircle>
<ProgressCircle percent={75} style={{ '--track-width': '3px' }}>
75%
</ProgressCircle>
<ProgressCircle percent={75} style={{ '--track-width': '4px' }}>
75%
</ProgressCircle>
</Space>
</div>
</div>
);
};
|
hqwlkj/umi-antd-mobile
|
src/pages/404.tsx
|
<filename>src/pages/404.tsx<gh_stars>10-100
export default ()=>{
return <div>404</div>
}
|
hqwlkj/umi-antd-mobile
|
config/routes.ts
|
<gh_stars>10-100
/**
* 路由配置
* 更多路由请查询 https://umijs.org/zh-CN/docs/routing
*/
export default [
{ exact: true, path: '/', redirect: '/tabBar/index' },
{
path: '/',
component: '@/layouts/index', // 采用umi 约定的全局路由, 因为umi不能针对不同的路由配置不同的 layout,所以需要在全局的layout中特殊处理。
routes: [
{
path: '/tabBar/index',
title: '首页',
icon: 'AlipayCircleFill',
component: '@/pages/home/index',
},
{
path: '/tabBar/todo',
title: '我的待办',
badgeKey: 'todoBadge',
icon: 'UnorderedListOutline',
wrappers: [
// 配置路由的高阶组件封装
'@/authority/index', //用于路由级别的权限校验
],
component: '@/pages/todo/index',
},
{
path: '/tabBar/message',
title: '我的消息',
icon: 'MessageOutline',
badgeKey: 'messageBadge',
wrappers: [
// 配置路由的高阶组件封装
'@/authority/index', //用于路由级别的权限校验
],
component: '@/pages/message/index',
},
{
path: '/tabBar/personalCenter',
title: '个人中心',
icon: 'UserOutline',
wrappers: [
// 配置路由的高阶组件封装
'@/authority/index', //用于路由级别的权限校验
],
component: '@/pages/account/index',
},
{ path: '/detail', title: '详情页', component: '@/pages/details/index' },
{ path: '/login', component: '@/pages/login/index' },
{ path: '/*', component: '@/pages/404' },
{ path: '/**/*', redirect: '/404' },
],
},
];
|
hqwlkj/umi-antd-mobile
|
src/pages/todo/index.tsx
|
<reponame>hqwlkj/umi-antd-mobile<gh_stars>10-100
import { Badge, List, Switch } from 'antd-mobile';
import {
PayCircleOutline,
SetOutline,
UnorderedListOutline,
} from 'antd-mobile-icons';
import React, { useCallback, useContext, useState } from 'react';
import { TabBarContext } from '@/layouts';
import { useHistory } from 'umi';
const Todo = () => {
const todo = useContext(TabBarContext);
const history = useHistory();
const [count, setCount] = useState(0);
const addTodoList = useCallback(() => {
todo.callback &&
todo.callback({
...todo.items,
todoBadge: Math.floor(Math.random() * 100 + 1),
});
}, [todo]);
const addMessage = useCallback(() => {
todo.callback && todo.callback({ ...todo.items, messageBadge: Badge.dot });
}, [todo]);
const closeAllBadge = useCallback(() => {
todo.callback && todo.callback({ messageBadge: null, todoBadge: null });
}, [todo]);
return (
<>
<List header="TabBar Badge 显示控制">
<List.Item
onClick={() => addTodoList()}
extra="随机显示一个0~100以内的数字"
>
增加我的代办
</List.Item>
<List.Item
onClick={() => {
setCount(count + 1);
todo.callback &&
todo.callback({
...todo.items,
messageBadge: count + 1 >= 20 ? '20+' : count + 1,
});
}}
extra="消息tab显示具体条数,最大20+"
>
增加消息
</List.Item>
<List.Item onClick={() => addMessage()} extra="消息tab显示红点">
增加消息
</List.Item>
<List.Item
onClick={() => closeAllBadge()}
extra="清空全部的 Badge 显示"
>
清楚全部
</List.Item>
<List.Item onClick={() => history.push('/detail')} extra="跳转到详情页">
在其他页面展示数据
</List.Item>
</List>
<List header="可点击的功能列表">
<List.Item prefix={<UnorderedListOutline />} onClick={() => {}}>
账单
</List.Item>
<List.Item prefix={<PayCircleOutline />} onClick={() => {}}>
总资产
</List.Item>
<List.Item prefix={<SetOutline />} onClick={() => {}}>
设置
</List.Item>
</List>
<List header="复杂布局">
<List.Item extra={<Switch defaultChecked />}>新消息通知</List.Item>
<List.Item extra="未开启" clickable>
大字号模式
</List.Item>
<List.Item description="管理已授权的产品和设备" clickable>
授权管理
</List.Item>
<List.Item title="这里是标题">这里是主信息</List.Item>
</List>
<List header="列表项禁用">
<List.Item disabled clickable prefix={<UnorderedListOutline />}>
账单
</List.Item>
<List.Item disabled prefix={<PayCircleOutline />}>
总资产
</List.Item>
</List>
</>
);
};
Todo.title = 'TOTO';
Todo.icon = 'toto-icon';
Todo.badge = '5';
export default Todo;
|
hqwlkj/umi-antd-mobile
|
src/components/index.ts
|
import Icon, { createFromIconfontCN } from './icons';
const UmiAntdMobileIcon = createFromIconfontCN({
scriptUrl: '//at.alicdn.com/t/font_3162733_un2ldgoxap.js', // 在 iconfont.cn 上生成
});
export { Icon, UmiAntdMobileIcon };
|
hqwlkj/umi-antd-mobile
|
src/pages/home/index.tsx
|
<gh_stars>10-100
import { Button, Grid, Popover, Space, Swiper, Toast } from 'antd-mobile';
import { useHistory } from 'umi';
import {
AddCircleOutline,
AntOutline,
DownOutline,
FolderOutline,
ReceivePaymentOutline,
RightOutline,
ScanningOutline,
SearchOutline,
TravelOutline,
UploadOutline,
UserContactOutline,
} from 'antd-mobile-icons';
import styles from './index.less';
export default function IndexPage() {
const history = useHistory();
const colors = ['#ace0ff', '#bcffbd', '#e4fabd', '#ffcfac'];
const items = colors.map((color, index) => (
<Swiper.Item key={index}>
<div
className={styles.content}
style={{ background: color }}
onClick={() => {
Toast.show(`你点击了卡片 ${index + 1}`);
}}
>
{index + 1}
</div>
</Swiper.Item>
));
return (
<div className={styles.homeWarp}>
<div className={styles.header}>
<Grid columns={12}>
<Grid.Item span={2}>
<div className={styles.location}>
<div className={styles.locationName}>
重庆
<DownOutline />
</div>
<div className={styles.weather}>多云 9℃</div>
</div>
</Grid.Item>
<Grid.Item span={8}>
<div className={styles.searchBarWarp}>
<SearchOutline className={styles.icon} />
<div className={styles.content}>
<Swiper
direction="vertical"
style={{ '--height': '30px' }}
autoplay={true}
loop={true}
indicator={() => null}
>
<Swiper.Item>
<div className={styles.verticalContent}>
重庆市第九人民医院
</div>
</Swiper.Item>
<Swiper.Item>
<div className={styles.verticalContent}>
重庆市卫健委发布重要通知
</div>
</Swiper.Item>
</Swiper>
</div>
<div className={styles.text}>搜索</div>
</div>
</Grid.Item>
<Grid.Item span={2}>
<div className={styles.expand}>
<Popover
content={
<div className={styles.expandMenuWarp}>
<div className={styles.menuItem}>
<ScanningOutline className={styles.icon} />
<div className={styles.menuItemInner}>扫一扫</div>
</div>
<div className={styles.menuItem}>
<ReceivePaymentOutline className={styles.icon} />
<div className={styles.menuItemInner}>二维码收款</div>
</div>
<div className={styles.menuItem}>
<UserContactOutline className={styles.icon} />
<div className={styles.menuItemInner}>我的名片</div>
</div>
<div className={styles.menuItem}>
<AntOutline className={styles.icon} />
<div className={styles.menuItemInner}>智能助理</div>
</div>
</div>
}
placement="topRight"
mode="dark"
trigger="click"
>
<AddCircleOutline />
</Popover>
</div>
</Grid.Item>
</Grid>
<Grid columns={4}>
<Grid.Item className={styles.iconWarp}>
<ScanningOutline />
<div className={styles.iconText}>扫一扫</div>
</Grid.Item>
<Grid.Item className={styles.iconWarp}>
<ReceivePaymentOutline />
<div className={styles.iconText}>收付款</div>
</Grid.Item>
<Grid.Item className={styles.iconWarp}>
<TravelOutline />
<div className={styles.iconText}>出行</div>
</Grid.Item>
<Grid.Item className={styles.iconWarp}>
<FolderOutline />
<div className={styles.iconText}>卡包</div>
</Grid.Item>
</Grid>
</div>
<div className={styles.ribbonWarp}>
<Grid columns={5}>
{[
'饿了么',
'消费金',
'市民中心',
'芭芭农场',
'蚂蚁森林',
'转账',
'汇率换算',
'余额宝',
'蚂蚁新村',
'生活缴费',
'花呗',
'健康码',
'运动',
'我的小程序',
'更多',
].map((text, index) => (
<Grid.Item
className={styles.iconWarp}
key={`item-${index}`}
onClick={() => history.push('/detail')}
>
<ScanningOutline />
<div className={styles.iconText}>{text}</div>
</Grid.Item>
))}
</Grid>
</div>
<div className={styles.messageWarp}>
<div className={styles.messageList}>
<div className={styles.messageItem}>
余额宝:余额宝收益到账啦 <span>7分钟前</span>
</div>
<div className={styles.messageItem}>
蚂蚁财富:你的基金收益已更新 <span>15分钟前</span>
</div>
</div>
<div className={styles.messageArrow}>
<RightOutline />
</div>
</div>
<div className={styles.adWarp}>
<Swiper autoplay={true} loop={true}>
{items}
</Swiper>
</div>
<div>
<Space wrap>
<Button
onClick={() =>
Toast.show({
icon: 'success',
content: '保存成功',
})
}
>
成功
</Button>
<Button
onClick={() => {
Toast.show({
icon: 'fail',
content: '名称已存在',
});
}}
>
失败
</Button>
<Button
onClick={() => {
Toast.show({
icon: 'loading',
content: '加载中…',
});
}}
>
加载中
</Button>
<Button
onClick={() => {
Toast.show({
content: '上传中',
icon: <UploadOutline />,
});
}}
>
自定义图标
</Button>
</Space>
</div>
</div>
);
}
|
hqwlkj/umi-antd-mobile
|
src/components/icons/Icon.tsx
|
import React, { useContext, useEffect } from 'react';
import classNames from 'classnames';
import IconContext from './Context';
import { updateCSS } from './utils/dynamicCSS';
// These props make sure that the SVG behaviours like general text.
// Reference: https://blog.prototypr.io/align-svg-icons-to-text-and-say-goodbye-to-font-icons-d44b3d7b26b4
export const svgBaseProps = {
width: '2em',
height: '2em',
fill: 'currentColor',
'aria-hidden': 'true',
focusable: 'false',
};
export const iconStyles = `
.anticon {
display: inline-block;
color: inherit;
font-style: normal;
line-height: 0;
text-align: center;
text-transform: none;
vertical-align: -0.125em;
text-rendering: optimizeLegibility;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
}
.anticon > * {
line-height: 1;
}
.anticon svg {
display: inline-block;
}
.anticon::before {
display: none;
}
.anticon .anticon-icon {
display: block;
}
.anticon[tabindex] {
cursor: pointer;
}
.anticon-spin::before,
.anticon-spin {
display: inline-block;
-webkit-animation: loadingCircle 1s infinite linear;
animation: loadingCircle 1s infinite linear;
}
@-webkit-keyframes loadingCircle {
100% {
-webkit-transform: rotate(360deg);
transform: rotate(360deg);
}
}
@keyframes loadingCircle {
100% {
-webkit-transform: rotate(360deg);
transform: rotate(360deg);
}
}
`;
export const useInsertStyles = (styleStr: string = iconStyles) => {
const { csp } = useContext(IconContext);
useEffect(() => {
updateCSS(styleStr, '@umi-antd-mobile-icons', {
prepend: true,
csp,
});
}, []);
};
export interface IconBaseProps extends React.HTMLProps<HTMLSpanElement> {
spin?: boolean;
rotate?: number;
}
export interface CustomIconComponentProps {
width: string | number;
height: string | number;
fill: string;
viewBox?: string;
className?: string;
style?: React.CSSProperties;
}
export interface IconComponentProps extends IconBaseProps {
viewBox?: string;
component?:
| React.ComponentType<
CustomIconComponentProps | React.SVGProps<SVGSVGElement>
>
| React.ForwardRefExoticComponent<CustomIconComponentProps>;
ariaLabel?: React.AriaAttributes['aria-label'];
}
const Icon = React.forwardRef<HTMLSpanElement, IconComponentProps>(
(props, ref) => {
const {
// affect outter <i>...</i>
className,
// affect inner <svg>...</svg>
component: Component,
viewBox,
spin,
rotate,
tabIndex,
onClick,
// children
children,
...restProps
} = props;
console.warn(
Boolean(Component || children),
'Should have `component` prop or `children`.',
);
useInsertStyles();
const { prefixCls = 'anticon' } = React.useContext(IconContext);
const classString = classNames(prefixCls, className);
const svgClassString = classNames({
[`${prefixCls}-spin`]: !!spin,
});
const svgStyle = rotate
? {
msTransform: `rotate(${rotate}deg)`,
transform: `rotate(${rotate}deg)`,
}
: undefined;
const innerSvgProps: CustomIconComponentProps = {
...svgBaseProps,
className: svgClassString,
style: svgStyle,
viewBox,
};
if (!viewBox) {
delete innerSvgProps.viewBox;
}
// component > children
const renderInnerNode = () => {
if (Component) {
return <Component {...innerSvgProps}>{children}</Component>;
}
if (children) {
console.warn(
Boolean(viewBox) ||
(React.Children.count(children) === 1 &&
React.isValidElement(children) &&
React.Children.only(children).type === 'use'),
'Make sure that you provide correct `viewBox`' +
' prop (default `0 0 1024 1024`) to the icon.',
);
return (
<svg {...innerSvgProps} viewBox={viewBox}>
{children}
</svg>
);
}
return null;
};
let iconTabIndex = tabIndex;
if (iconTabIndex === undefined && onClick) {
iconTabIndex = -1;
}
return (
<span
role="img"
{...restProps}
ref={ref}
tabIndex={iconTabIndex}
onClick={onClick}
className={classString}
>
{renderInnerNode()}
</span>
);
},
);
Icon.displayName = 'UmiAntdMobileIcon';
export default Icon;
|
hqwlkj/umi-antd-mobile
|
src/app.ts
|
import 'antd-mobile/es/global';
import './theme.less';
|
hqwlkj/umi-antd-mobile
|
src/pages/message/index.tsx
|
import { Grid, NoticeBar, Space } from 'antd-mobile';
import { CloseCircleOutline, CompassOutline } from 'antd-mobile-icons';
import { UmiAntdMobileIcon } from '@/components';
export default () => {
return (
<>
<Space block direction="vertical">
<NoticeBar content="默认" color="default" />
<NoticeBar content="警告" color="alert" />
<NoticeBar content="错误" color="error" />
<NoticeBar content="信息" color="info" />
<NoticeBar
content="超长滚动超长滚动超长滚动超长滚动超长滚动超长滚动超长滚动超长滚动超长滚动"
color="alert"
/>
<NoticeBar content="这条通知可以关闭" color="alert" closeable />
<NoticeBar
extra={<CloseCircleOutline style={{ fontSize: 18 }} />}
icon={<CompassOutline />}
content={'自定义图标'}
/>
<NoticeBar
extra={
<Space style={{ '--gap': '12px' }}>
<span>查看详情</span>
<span>关闭</span>
</Space>
}
content={'自定义右侧功能区'}
color="alert"
/>
</Space>
<div>自定义icon</div>
<Grid columns={6}>
<Grid.Item>
<UmiAntdMobileIcon type="icon-windows-fill" />
</Grid.Item>
<Grid.Item>
<UmiAntdMobileIcon type="icon-QQ" />
</Grid.Item>
<Grid.Item>
<UmiAntdMobileIcon type="icon-twitter" />
</Grid.Item>
<Grid.Item>
<UmiAntdMobileIcon type="icon-skype-fill" />
</Grid.Item>
<Grid.Item>
<UmiAntdMobileIcon type="icon-alipay-circle-fill" />
</Grid.Item>
<Grid.Item>
<UmiAntdMobileIcon type="icon-github-fill" />
</Grid.Item>
<Grid.Item>
<UmiAntdMobileIcon type="icon-dribbble-circle-fill" />
</Grid.Item>
<Grid.Item>
<UmiAntdMobileIcon type="icon-twitter-circle-fill" />
</Grid.Item>
</Grid>
</>
);
};
|
hqwlkj/umi-antd-mobile
|
src/pages/account/index.tsx
|
<reponame>hqwlkj/umi-antd-mobile<gh_stars>10-100
import {
Avatar,
Badge,
DotLoading,
List,
NavBar,
PullToRefresh,
Space,
} from 'antd-mobile';
import {
AlipayCircleFill,
AntOutline,
BankcardOutline,
CheckShieldOutline,
ContentOutline,
CouponOutline,
FileOutline,
FireFill,
GiftOutline,
HandPayCircleOutline,
HistogramOutline,
KoubeiFill,
MoreOutline,
PayCircleOutline,
PieOutline,
ReceiptOutline,
SetOutline,
UserCircleOutline,
} from 'antd-mobile-icons';
import styles from './index.less';
import { useState } from 'react';
import { sleep } from 'antd-mobile/es/utils/sleep';
export default () => {
const listData = [
[
{
icon: <AntOutline className="icon-1" />,
title: (
<span>
支付宝会员 {' '}
<Badge
content={
<span>
{' '}
<AntOutline /> 钻石会员
</span>
}
/>
</span>
),
extra: '',
},
{
icon: <CheckShieldOutline className="icon-1" />,
title: '用户保护中心',
extra: '',
},
{
icon: <CouponOutline className="icon-1" />,
title: '商家服务',
extra: '',
},
],
[
{
icon: <FileOutline className="icon-2" />,
title: '账单',
extra: '',
},
{
icon: <PieOutline className="icon-1" />,
title: '总资产',
extra: <span className="extra-1">免费升级账户保障</span>,
},
{
icon: <PayCircleOutline className="icon-1" />,
title: '余额',
extra: <span className="extraDefault">5.00</span>,
},
{
icon: <HandPayCircleOutline className="icon-3" />,
title: '余额宝',
extra: '',
},
{
icon: <HistogramOutline className="icon-1" />,
title: '花呗',
extra: '',
},
{
icon: <ContentOutline className="icon-1" />,
title: '余利宝',
extra: '',
},
{
icon: <BankcardOutline className="icon-2" />,
title: '银行卡',
extra: '',
},
],
[
{
icon: <AntOutline className="icon-1" />,
title: '芝麻信用',
extra: (
<Badge content={Badge.dot} style={{ '--top': '50%' }}>
<span className="extraDefault">有芝麻粒待积攒 </span>
</Badge>
),
},
{
icon: <AlipayCircleFill className="icon-1" />,
title: '蚂蚁保',
extra: '',
},
{
icon: <FireFill className="icon-3" />,
title: '相互宝',
extra: '',
},
{
icon: <ReceiptOutline className="icon-1" />,
title: '网商贷',
extra: '',
},
{
icon: <KoubeiFill className="icon-1" />,
title: '网商银行',
extra: '',
},
],
[
{
icon: <GiftOutline className="icon-1" />,
title: '我的公益',
extra: '',
},
],
];
const right = (
<div style={{ fontSize: 24 }}>
<Space style={{ '--gap': '16px', color: '#ffffff' }}>
<UserCircleOutline />
<SetOutline />
</Space>
</div>
);
const getNextData = () => {
let current = 1;
const ret: string[] = [];
for (let i = 0; i < 18; i++) {
ret.unshift(current.toString());
current++;
}
return ret;
};
const [data, setData] = useState(() => getNextData());
return (
<div className={styles.account}>
<NavBar
right={right}
back={null}
left={<span className={styles.leftTitle}>我的</span>}
/>
<div className={styles.body}>
<PullToRefresh
renderText={(status) => {
switch (status) {
case 'pulling':
return (
<div className={styles.reshingWarp}>
<MoreOutline color="currentColor" />
</div>
);
case 'canRelease':
return (
<div className={styles.reshingWarp}>
<div>松开刷新</div>
<MoreOutline color="currentColor" />
</div>
);
case 'refreshing':
return (
<div className={styles.reshingWarp}>
<DotLoading color="currentColor" />
</div>
);
case 'complete':
return '';
default:
return '';
}
}}
onRefresh={async () => {
await sleep(2000);
setData([...getNextData(), ...data]);
}}
>
<div className={styles.headerWarp}>
<List>
<List.Item
prefix={
<Avatar
src={
'https://images.unsplash.com/photo-1546967191-fdfb13ed6b1e?ixlib=rb-1.2.1&q=80&fm=jpg&crop=faces&fit=crop&h=200&w=200&ixid=eyJhcHBfaWQiOjE3Nzg0fQ'
}
/>
}
description="<EMAIL>"
onClick={() => {}}
>
<NAME>
</List.Item>
</List>
</div>
{listData.map((group, i) => {
return (
<div className={styles.listGroupWarp} key={`list-group-${i}`}>
<List mode="card">
{group.map((item, j) => (
<List.Item
key={`list-item-${i}-${j}`}
prefix={item.icon}
onClick={() => {}}
extra={item.extra}
>
{item.title}
</List.Item>
))}
</List>
</div>
);
})}
</PullToRefresh>
</div>
</div>
);
};
|
hqwlkj/umi-antd-mobile
|
src/components/icons/index.ts
|
import Context from '@/components/icons/Context';
export { default as createFromIconfontCN } from './IconFont';
export { default } from '@/components/icons/Icon';
const IconProvider = Context.Provider;
export { IconProvider };
|
hqwlkj/umi-antd-mobile
|
src/layouts/index.tsx
|
import type { IRouteComponentProps } from 'umi';
import React, { useMemo, useState } from 'react';
import type { BadgeProps } from 'antd-mobile/es/components/badge';
import TabBarLayout from './tab-bar';
import './index.less';
export interface TabBarItemValueProps {
homeBadge?: BadgeProps['content'];
todoBadge?: BadgeProps['content'];
messageBadge?: BadgeProps['content'];
meBadge?: BadgeProps['content'];
}
export const TabBarContext = React.createContext<{
items: TabBarItemValueProps;
callback?: (values: TabBarItemValueProps) => void;
}>({
items: {},
});
/**
* 不同的全局 layout
* @param props
* @url https://umijs.org/zh-CN/docs/convention-routing#%E4%B8%8D%E5%90%8C%E7%9A%84%E5%85%A8%E5%B1%80-layout
*/
export default (props: IRouteComponentProps) => {
const [taBarItemValues, setTabBarItemValues] = useState<
TabBarItemValueProps | any
>({});
const getLayoutChildren = useMemo(() => {
if (props.location.pathname.includes('/tabBar/')) {
console.log('====== TabBarLayout ======');
return <TabBarLayout {...props}>{props.children}</TabBarLayout>;
}
console.log('basic-layout-warp');
return <div className="basic-layout-warp">{props.children}</div>;
}, [props]);
return (
<TabBarContext.Provider
value={{
items: taBarItemValues,
callback: (items) => setTabBarItemValues({ ...items }),
}}
>
<div className="global-layout">{getLayoutChildren}</div>
</TabBarContext.Provider>
);
};
|
hqwlkj/umi-antd-mobile
|
src/pages/loading.tsx
|
import React from 'react';
import '../app.less';
import { SpinLoading } from 'antd-mobile';
/**
* 如何禁用掉每次刷新路由时出现的 loading... 状态?
* https://umijs.org/zh-CN/docs/faq#%E5%A6%82%E4%BD%95%E7%A6%81%E7%94%A8%E6%8E%89%E6%AF%8F%E6%AC%A1%E5%88%B7%E6%96%B0%E8%B7%AF%E7%94%B1%E6%97%B6%E5%87%BA%E7%8E%B0%E7%9A%84-loading-%E7%8A%B6%E6%80%81%EF%BC%9F
*/
export default () => {
return (
<div className="loading-warp">
<div>
<SpinLoading color="primary" />
</div>
<div className="loading-warp-text">加载中...</div>
</div>
);
};
|
hqwlkj/umi-antd-mobile
|
src/layouts/tab-bar/index.tsx
|
import React, { useCallback, useContext, useEffect, useState } from 'react';
import { TabBar } from 'antd-mobile';
import type { TabBarItemProps } from 'antd-mobile/es/components/tab-bar';
import type { IRouteComponentProps } from 'umi';
import {
AlipayCircleFill,
AppOutline,
MessageFill,
UnorderedListOutline,
UserOutline,
} from 'antd-mobile-icons';
import styles from './index.less';
import { TabBarContext } from '@/layouts';
export default ({
children,
route,
history,
location,
}: IRouteComponentProps) => {
const [tabs, setTabs] = useState<TabBarItemProps[] | any[]>([]);
const [activeKey, setActiveKey] = useState<string>('');
const tabBarContext = useContext(TabBarContext);
useEffect(() => {
const { pathname } = location;
if (route) {
const { routes } = route as any;
const _tabs = (routes || [])
.filter((x: any) => !!x.icon)
.map((_route: any) => ({
key: (_route.path || '').replace('/', ''),
title: _route.title,
icon: _route.icon,
badge: _route.badgeKey,
}));
if (pathname) {
setActiveKey(pathname.replace('/', ''));
} else {
setActiveKey(_tabs[0].key);
}
setTabs(_tabs);
}
}, [route, location]);
const renderTabItemIcon = useCallback((name: string) => {
switch (name) {
case 'AppOutline':
return <AppOutline />;
case 'AlipayCircleFill':
return <AlipayCircleFill />;
case 'UnorderedListOutline':
return <UnorderedListOutline />;
case 'MessageFill':
return <MessageFill />;
case 'MessageOutline':
return <MessageFill />;
case 'UserOutline':
return <UserOutline />;
default:
return '';
}
}, []);
return (
<div className={styles['tab-bar-layout']}>
<div className={styles['container-warp']}>
<div className={styles['view-warp']}>{children}</div>
</div>
<TabBar
activeKey={activeKey}
onChange={(key) => {
setActiveKey(key);
history.replace('/' + key);
}}
safeArea
>
{tabs.map((item) => (
<TabBar.Item
key={item.key}
icon={renderTabItemIcon(item.icon)}
title={item.title}
badge={tabBarContext.items[item.badge] || null}
/>
))}
</TabBar>
</div>
);
};
|
aks-/timber-js
|
packages/core/src/base.ts
|
<filename>packages/core/src/base.ts<gh_stars>0
import {
ITimberLog,
ITimberOptions,
LogLevel,
Middleware,
Sync
} from "@timberio/types";
import { makeBatch, makeThrottle } from "@timberio/tools";
// Set default options for Timber
const defaultOptions: ITimberOptions = {
// Default sync endpoint:
endpoint: "https://logs.timber.io/frames",
// Maximum number of logs to sync in a single request to Timber.io
batchSize: 1000,
// Max interval (in milliseconds) before a batch of logs proceeds to syncing
batchInterval: 1000,
// Maximum number of sync requests to make concurrently
syncMax: 5
};
/**
* Timber core class for logging to the Timber.io service
*/
class Timber {
// Timber API key
protected _apiKey: string;
// Timber library options
protected _options: ITimberOptions;
// Batch function
protected _batch: any;
// Middleware
protected _middleware: Middleware[] = [];
// Sync function
protected _sync?: Sync;
// Number of logs logged
private _countLogged = 0;
// Number of logs successfully synced with Timber
private _countSynced = 0;
/* CONSTRUCTOR */
/**
* Initializes a new Timber instance
*
* @param apiKey: string - Private API key for logging to Timber.io
* @param options?: ITimberOptions - Optionally specify Timber options
*/
public constructor(apiKey: string, options?: Partial<ITimberOptions>) {
// First, check we have a valid API key
if (typeof apiKey !== "string" || apiKey === "") {
throw new Error("Timber API key missing");
}
// Store the API key, to use for syncing with Timber.io
this._apiKey = apiKey;
// Merge default and user options
this._options = { ...defaultOptions, ...options };
// Create a throttler, for sync operations
const throttle = makeThrottle(this._options.syncMax);
// Sync after throttling
const throttler = throttle((logs: any) => {
return this._sync!(logs);
});
// Create a batcher, for aggregating logs by buffer size/interval
const batcher = makeBatch(
this._options.batchSize,
this._options.batchInterval
);
this._batch = batcher((logs: any) => {
return throttler(logs);
});
}
/* PUBLIC METHODS */
/**
* Number of entries logged
*
* @returns number
*/
public get logged(): number {
return this._countLogged;
}
/**
* Number of log entries synced with Timber.io
*
* @returns number
*/
public get synced(): number {
return this._countSynced;
}
/**
* Log an entry, to be synced with Timber.io
*
* @param message: string - Log message
* @param level (LogLevel) - Level to log at (debug|info|warn|error)
* @param log: (Partial<ITimberLog>) - Initial log (optional)
* @returns Promise<ITimberLog> after syncing
*/
public async log(
message: string,
level: LogLevel = LogLevel.Info,
log: Partial<ITimberLog> = {}
): Promise<ITimberLog> {
// Check that we have a sync function
if (typeof this._sync !== "function") {
throw new Error("No Timber logger sync function provided");
}
// Increment log count
this._countLogged++;
// Build the initial log
const initialLog: ITimberLog = {
// Implicit date timestamp
dt: new Date(),
// Overwrite defaults / add context, with `log` object
...log,
// Explicit level
level,
// Explicit message
message,
// Finally, add the definitive schema
$schema:
"https://raw.githubusercontent.com/timberio/log-event-json-schema/v4.1.0/schema.json"
};
// Pass the log through the middleware pipeline
const transformedLog = await this._middleware.reduceRight(
(fn, pipedLog) => fn.then(pipedLog),
Promise.resolve(initialLog)
);
// Push the log through the batcher, and sync
await this._batch(transformedLog);
// Increment sync count
this._countSynced++;
// Return the resulting log
return transformedLog;
}
/**
*
* Debug level log, to be synced with Timber.io
*
* @param message: string - Log message
* @param log: (Partial<ITimberLog>) - Initial log (optional)
* @returns Promise<ITimberLog> after syncing
*/
public async debug(
message: string,
log: Partial<ITimberLog> = {}
): Promise<ITimberLog> {
return this.log(message, LogLevel.Debug, log);
}
/**
*
* Info level log, to be synced with Timber.io
*
* @param message: string - Log message
* @param log: (Partial<ITimberLog>) - Initial log (optional)
* @returns Promise<ITimberLog> after syncing
*/
public async info(
message: string,
log: Partial<ITimberLog> = {}
): Promise<ITimberLog> {
return this.log(message, LogLevel.Info, log);
}
/**
*
* Warning level log, to be synced with Timber.io
*
* @param message: string - Log message
* @param log: (Partial<ITimberLog>) - Initial log (optional)
* @returns Promise<ITimberLog> after syncing
*/
public async warn(
message: string,
log: Partial<ITimberLog> = {}
): Promise<ITimberLog> {
return this.log(message, LogLevel.Warn, log);
}
/**
*
* Warning level log, to be synced with Timber.io
*
* @param message: string - Log message
* @param log: (Partial<ITimberLog>) - Initial log (optional)
* @returns Promise<ITimberLog> after syncing
*/
public async error(
message: string,
log: Partial<ITimberLog> = {}
): Promise<ITimberLog> {
return this.log(message, LogLevel.Error, log);
}
/**
* Sets the sync method - i.e. the final step in the pipeline to get logs
* over to Timber.io
*
* @param fn - Pipeline function to use as sync method
*/
public setSync(fn: Sync): void {
this._sync = fn;
}
/**
* Add a middleware function to the logging pipeline
*
* @param fn - Function to add to the log pipeline
* @returns void
*/
public use(fn: Middleware): void {
this._middleware.push(fn);
}
/**
* Remove a function from the pipeline
*
* @param fn - Pipeline function
* @returns void
*/
public remove(fn: Middleware): void {
this._middleware = this._middleware.filter(p => p !== fn);
}
}
// noinspection JSUnusedGlobalSymbols
export default Timber;
|
aks-/timber-js
|
packages/core/src/index.ts
|
import Base from "./base";
export {
/**
* Classes
*/
Base,
};
|
aks-/timber-js
|
packages/browser/src/browser.test.ts
|
<filename>packages/browser/src/browser.test.ts
import nock from "nock";
import { base64Encode } from "@timberio/tools";
import { ITimberLog, LogLevel } from "@timberio/types";
import { Browser, getUserAgent } from "./browser";
import * as pjson from "../package.json";
const { version } = pjson;
/**
* Create a log with a random string / current date
*/
function getRandomLog(message: string): Partial<ITimberLog> {
return {
message
};
}
describe("browser user-agent tests", () => {
it("should include version number in user-agent", () => {
const expectedValue = `timber-js/${version}`;
const actualValue = getUserAgent();
expect(actualValue).toEqual(expectedValue);
});
});
/**
* set new property btoa in node enviroment to run the tests
*/
const _global: any = global;
_global.btoa = base64Encode;
describe("browser tests", () => {
it("should echo log if timber sends 20x status code", async done => {
nock("https://logs.timber.io")
.post("/frames")
.reply(201);
const message: string = String(Math.random());
const expectedLog = getRandomLog(message);
const browser = new Browser("valid api key");
const echoedLog = await browser.log(message);
expect(echoedLog.message).toEqual(expectedLog.message);
done();
});
it("should throw error if timber sends non 200 status code", async done => {
nock("https://logs.timber.io")
.post("/frames")
.reply(401);
const browser = new Browser("invalid api key");
const message: string = String(Math.random);
await expect(browser.log(message)).rejects.toThrow();
done();
});
});
|
aks-/timber-js
|
packages/tools/src/batch.test.ts
|
<reponame>aks-/timber-js<filename>packages/tools/src/batch.test.ts
import nock from "nock";
import fetch from "cross-fetch";
import { ITimberLog, LogLevel } from "@timberio/types";
import makeBatch from "./batch";
import makeThrottle from "./throttle";
/**
* Create a log with a random string / current date
*/
function getRandomLog(): ITimberLog {
return {
$schema:
"https://raw.githubusercontent.com/timberio/log-event-json-schema/v4.1.0/schema.json",
dt: new Date(),
level: LogLevel.Info,
message: String(Math.random())
};
}
/**
* Returns an `n` sized array of logger functions
*
* @param logger - Logger function to pass in `getRandomLog()`
* @param n - Number of functions to return
*/
function logNumberTimes(logger: Function, n: number): Function[] {
return [...Array(n).keys()].map(() => logger(getRandomLog()));
}
/**
* Calculate end time in milliseconds
* @param start: [number, number] = NodeJS `process.hrtime` start time
*/
function calcEndTime(start: [number, number]): number {
const end = process.hrtime(start);
return (end[0] * 1e9 + end[1]) / 1e6;
}
describe("batch tests", () => {
it("should log warning if buffer size is lower than 5", () => {
const size = 3;
const sendTimeout = 1000;
const expectedWarning =
"warning: Gracefully fixing bad value of batch size to default 5";
const warning = jest.spyOn(global.console, "warn");
const batcher = makeBatch(size, sendTimeout);
expect(warning).toBeCalledWith(expectedWarning);
warning.mockRestore();
});
it("should log warning if flush timeout is lower than 1000", () => {
const size = 5;
const sendTimeout = 999;
const expectedWarning =
"warning: Gracefully fixing bad value of timeout to default 1000";
const warning = jest.spyOn(global.console, "warn");
jest.spyOn(global.console, "warn");
const batcher = makeBatch(size, sendTimeout);
expect(console.warn).toBeCalledWith(expectedWarning);
warning.mockRestore();
});
it("should use default buffer size value 5 when size is passed as undefined", () => {
const size = undefined;
const sendTimeout = 1000;
const warning = jest.spyOn(global.console, "warn");
const batcher = makeBatch(size, sendTimeout);
expect(console.warn).toHaveBeenCalledTimes(0);
warning.mockRestore();
});
it("should use default flush timeout value 1000 when passed as undefined", () => {
const size = 5;
const sendTimeout = undefined;
const warning = jest.spyOn(global.console, "warn");
const batcher = makeBatch(size, sendTimeout);
expect(console.warn).toHaveBeenCalledTimes(0);
warning.mockRestore();
});
it("should default to size of 5, if size is less than 5", async () => {
const size = 4;
const sendTimeout = 1000;
const batcher = makeBatch(size, sendTimeout);
const logger = batcher((batch: ITimberLog[]) => {
expect(batch.length).toEqual(5);
});
await Promise.all(logNumberTimes(logger, 5)).catch(e => {
throw e;
});
}, 1100);
it("should default to timeout of 1 sec, if timeout is less than that", done => {
const size = 6;
const sendTimeout = 10;
const batcher = makeBatch(size, sendTimeout);
const logger = batcher((batch: ITimberLog[]) => {
expect([2, 1].includes(batch.length)).toBeTruthy();
done();
});
logger(getRandomLog()).catch(e => {
throw e;
});
setTimeout(() => logger(getRandomLog()), 500);
setTimeout(() => logger(getRandomLog()), 1001);
}, 2100);
it("should flush the batch when batch length is one less than max possible size.", done => {
const size = 200;
const sendTimeout = 10;
const batcher = makeBatch(size, sendTimeout);
const logger = batcher((batch: ITimberLog[]) => {
expect([99, 2].includes(batch.length)).toBeTruthy();
done();
});
for (let i = 0; i <= 100; i++) {
logger(getRandomLog()).catch(e => {
throw e;
});
}
}, 1100);
it("should not fire timeout while a send was happening.", async done => {
nock("http://example.com")
.get("/")
.reply(200, new Promise(res => setTimeout(() => res(200), 1003)));
const called = jest.fn();
const size = 5;
const sendTimeout = 10;
const batcher = makeBatch(size, sendTimeout);
const logger = batcher(async (batch: ITimberLog[]) => {
called();
try {
await fetch("http://example.com");
} catch (e) {
throw e;
}
});
await Promise.all(logNumberTimes(logger, 5)).catch(e => {
throw e;
});
expect(called).toHaveBeenCalledTimes(1);
nock.restore();
done();
});
it("should handle another log that comes in while it's sending...", async done => {
nock("http://example.com")
.get("/")
.reply(200, new Promise(res => setTimeout(() => res(200), 1003)));
const called = jest.fn();
const size = 5;
const sendTimeout = 10;
const batcher = makeBatch(size, sendTimeout);
const logger = batcher(async () => {
called();
try {
await fetch("http://example.com");
} catch (e) {
throw e;
}
});
await Promise.all(logNumberTimes(logger, 6)).catch(e => {
throw e;
});
expect(called).toHaveBeenCalledTimes(2);
nock.restore();
done();
});
it("should play nicely with `throttle`", async () => {
// Fixtures
const maxThrottle = 2;
const throttleResolveAfter = 1000; // ms
const batchSize = 5;
const numberOfLogs = 20;
// Create a throttle that processes 1 pipeline at once
const throttle = makeThrottle(maxThrottle);
// Resolve the throttler after 1 second
const throttler = throttle(async logs => {
return new Promise(resolve => {
setTimeout(() => resolve(logs), throttleResolveAfter);
});
});
// Store the throttled promises in an array
const promises = [];
// Create a batcher that 'emits' after `batchSize` logs
const batch = makeBatch(batchSize, 5000);
// The batcher should be throttled
const batcher = batch((logs: any) => {
expect(logs.length).toEqual(batchSize);
return throttler(logs);
});
// Start the timer
const start = process.hrtime();
// Fire off a bunch of logs into the batcher
for (let i = 0; i < numberOfLogs; i++) {
promises.push(batcher(getRandomLog()));
}
// Await batching and throttling
await Promise.all(promises);
// Get the time once all promises have been fulfilled
const end = calcEndTime(start);
// Expect time to have taken at least this long...
const expectedTime =
((numberOfLogs / batchSize) * throttleResolveAfter) / maxThrottle;
expect(end).toBeGreaterThanOrEqual(expectedTime);
});
});
|
aks-/timber-js
|
packages/tools/src/retry.ts
|
import { ITimberLog } from "@timberio/types";
/**
* maximum number of tries to push logs to timberio
*/
let MAX_TRIES = 3;
/**
* delays excution of function by `sec` seconds.
*
* @param sec - Number
*/
function delay(sec: number): Promise<any> {
return new Promise(resolve => setTimeout(resolve, sec * 1000));
}
/**
* tries to process logs maximum 3 times in case of server error.
*
* @param fn - (logs: ITimberLog[]) => Promise<ITimberLog[]>
*/
export default async function makeRetry(
fn: (logs: ITimberLog[]) => Promise<ITimberLog[]>
) {
/**
* number of retries
*/
let tries: number = 0;
/**
* list of try time in seconds
*/
let timeouts: number[] = [0, 1];
/**
* pushes logs for process function
* @param logs - ITimberLog[]
*/
return async function retry(logs: ITimberLog[]): Promise<ITimberLog[]> {
//TODO: retry only when there is server error.
while (tries++ < MAX_TRIES) {
try {
/**
* returns Fibonacci timeout based on try time list
*/
const timeout = timeouts
.slice()
.reverse()
.slice(0, 2)
.reduce((acc, curr) => acc + curr, 0);
timeouts.push(timeout);
await delay(timeout);
return await fn(logs);
} catch (e) {
/**
* throw error if could not process logs all three tries
*/
if (tries === MAX_TRIES) {
throw e;
}
}
}
return Promise.resolve(logs);
};
}
|
aks-/timber-js
|
packages/node/src/node.ts
|
import fetch from "cross-fetch";
// import Msgpack from "msgpack5";
import { base64Encode } from "@timberio/tools";
import { ITimberLog, ITimberOptions } from "@timberio/types";
import { Base } from "@timberio/core";
import * as pjson from "../package.json";
const { version } = pjson;
export function getUserAgent(): string {
return `timber-js/${version}`;
}
// Namespace the msgpack library
// const msgpack = Msgpack();
export class Node extends Base {
public constructor(apiKey: string, options?: Partial<ITimberOptions>) {
super(apiKey, options);
// TODO - remove this in production... dump out the env for dev!
console.log("Hello from Node!");
// Sync function
const sync = async (logs: ITimberLog[]): Promise<ITimberLog[]> => {
// TODO - obviously, this doesn't conform perfectly to the spec
// yet... dev only!
const res = await fetch(this._options.endpoint, {
method: "POST",
headers: {
// "Content-Type": "application/msgpack",
"Content-Type": "text/plain",
Authorization: `Basic ${base64Encode(this._apiKey)}`,
"User-Agent": getUserAgent(),
},
// body: logs.map(log => `${log.level}: ${log.message}`).join("\n")
// body: msgpack.encode(logsWithSchema).slice()
body: JSON.stringify(logs)
});
if (res.ok) {
return logs;
}
/**
* TODO: if status is 50x throw custom ServerError
* to be used in retry logic
*/
throw new Error(res.statusText);
};
// Set the throttled sync function
this.setSync(sync);
}
}
|
aks-/timber-js
|
packages/core/src/base.test.ts
|
import Base from "./base";
import { ITimberLog, LogLevel } from "@timberio/types";
describe("base class tests", () => {
it("should initialize with API key", () => {
const apiKey = "testing";
const base = new Base(apiKey);
expect((base as any)._apiKey).toEqual(apiKey);
});
it("should throw if a `sync` method is missing", async () => {
const base = new Base("testing");
// Expect logging to throw an error, since we're missing a `sync` func
await expect(base.log("Test")).rejects.toThrowError(/sync/);
});
it("should add an implicit `dt` timestamp", async () => {
// Fixtures
const message = "Test";
const base = new Base("testing");
// Add a mock sync method
base.setSync(async logs => logs);
// Pass the log through the `.log()` function and get the result
const result = await base.log(message);
// Expect the message to be same
expect(result.message).toEqual(message);
// ... but a new `date` should be added
expect(result.dt).not.toBeUndefined();
});
it("should default log count to zero", () => {
const base = new Base("testing");
expect(base.logged).toEqual(0);
});
it("should default synced count to zero", () => {
const base = new Base("testing");
expect(base.synced).toEqual(0);
});
it("should increment log count on `.log()`", async () => {
const base = new Base("testing");
// Add a mock sync method
base.setSync(async log => log);
void (await base.log("Test"));
// Logged count should now be 1
expect(base.logged).toEqual(1);
});
it("should sync after 500 ms", async () => {
const base = new Base("testing");
// Create a sync function that resolves after 500ms
base.setSync(async log => {
return new Promise<ITimberLog[]>(resolve => {
setTimeout(() => {
resolve(log);
}, 500);
});
});
// Fire the log event, and store the pending promise
const pending = base.log("Test");
// The log count should be 1
expect(base.logged).toEqual(1);
// ... but synced should still be zero
expect(base.synced).toEqual(0);
// Await the pending sync
void (await pending);
// After 500ms, synced should be now be 1
expect(base.synced).toEqual(1);
});
it("should add a pipeline function", async () => {
// Fixtures
const firstMessage = "First message";
const base = new Base("testing");
// Add a mock sync method
base.setSync(async log => log);
// Message to replacement with
const newMessage = "Second message";
// Add a custom pipeline that replaces `message`
base.use(async log => {
return {
...log,
message: newMessage
};
});
// Get the resulting log
const result = await base.log(firstMessage);
// The resulting message should equal the new message
expect(result.message).toEqual(newMessage);
});
it("should remove a pipeline function", async () => {
const base = new Base("testing");
// Create a pipeline function
const customPipeline = async (log: ITimberLog) => log;
// Add the pipeline
base.use(customPipeline);
// Confirm that it exists in the `_pipeline` array
expect((base as any)._middleware).toContain(customPipeline);
// Remove the pipeline
base.remove(customPipeline);
// Confirm that it has disappeared from the array
expect((base as any)._middleware).not.toContain(customPipeline);
});
it("should default to 'info' level logging", async () => {
// Fixtures
const message = "Test";
const base = new Base("testing");
// Add a mock sync method
base.setSync(async log => log);
// Log
const log = await base.log(message);
// Should log at 'info' level
expect(log.level).toEqual(LogLevel.Info);
});
it("should handle 'debug' logging", async () => {
// Fixtures
const message = "Test";
const base = new Base("testing");
// Add a mock sync method
base.setSync(async log => log);
// Log
const log = await base.debug(message);
// Should log at 'debug' level
expect(log.level).toEqual(LogLevel.Debug);
});
it("should handle 'info' logging", async () => {
// Fixtures
const message = "Test";
const base = new Base("testing");
// Add a mock sync method
base.setSync(async log => log);
// Log
const log = await base.info(message);
// Should log at 'info' level
expect(log.level).toEqual(LogLevel.Info);
});
it("should handle 'warn' logging", async () => {
// Fixtures
const message = "Test";
const base = new Base("testing");
// Add a mock sync method
base.setSync(async log => log);
// Log
const log = await base.warn(message);
// Should log at 'info' level
expect(log.level).toEqual(LogLevel.Warn);
});
it("should handle 'error' logging", async () => {
// Fixtures
const message = "Test";
const base = new Base("testing");
// Add a mock sync method
base.setSync(async log => log);
// Log
const log = await base.error(message);
// Should log at 'info' level
expect(log.level).toEqual(LogLevel.Error);
});
});
|
lucacasonato/cors-playground
|
router.ts
|
import { getOwn } from './util.ts';
export type RouteHandler = (
url: URL,
request: Request,
) => Promise<Response> | Response;
type Route = RouteHandler | { [method: string]: RouteHandler };
const router = new Map<string, Route>();
function getRouteFunction(
route: Route,
method: string,
): RouteHandler | undefined {
if (typeof route === 'function') {
if (method === 'GET') return route;
return undefined;
}
return getOwn(route, method) || getOwn(route, 'all');
}
export const simpleErrorResponse = (status: number, message: string) =>
new Response(message, {
status,
headers: { 'Content-Type': 'text/plain' },
});
async function handleRequest(request: Request): Promise<Response> {
const url = new URL(request.url);
const route = router.get(url.pathname);
if (!route) return simpleErrorResponse(404, 'Not found');
const routeHandler = getRouteFunction(route, request.method);
if (!routeHandler) return simpleErrorResponse(405, 'Method not allowed');
try {
return await routeHandler(url, request);
} catch (error) {
console.log(error);
return simpleErrorResponse(500, 'Internal server error');
}
}
export function addRoute(path: string, route: Route) {
router.set(path, route);
}
addEventListener('fetch', (event) =>
event.respondWith(handleRequest(event.request)),
);
|
lucacasonato/cors-playground
|
util.ts
|
<filename>util.ts
/**
* Get own property `prop` from `obj`.
*/
export const getOwn = <T, P extends keyof T>(
obj: T,
prop: P,
): T[P] | undefined =>
Object.prototype.hasOwnProperty.call(obj, prop) ? obj[prop] : undefined;
|
tarikub/opFaceMask
|
opFaceMask.Web/ClientApp/src/app/app.component.ts
|
import { Component, ViewChild, ElementRef, OnInit } from "@angular/core";
import { HubConnection } from "@aspnet/signalr";
import * as signalR from "@aspnet/signalr";
declare const google: any;
@Component({
selector: "app-root",
templateUrl: "./app.component.html",
styleUrls: ["./app.component.css"],
})
export class AppComponent implements OnInit {
private hubConnection: HubConnection;
private bindConnectionMessage(connection) {
var messageCallback = function (location: {
Address: string;
Lat: string;
Lng: string;
}, message) {
if (!location) return;
const newCoordinates = new google.maps.LatLng(location.Lat, location.Lng);
const marker = new google.maps.Marker({
position: newCoordinates,
map: this.map,
animation: google.maps.Animation.DROP
});
marker.setMap(this.map);
};
// Create a function that the hub can call to broadcast messages.
connection.on("broadcastMessage", messageCallback.bind(this));
connection.on("echo", messageCallback.bind(this));
connection.onclose(this.onConnectionError.bind(this));
}
private onConnectionError(error) {
if (error && error.message) {
console.error(error.message);
}
}
ngOnInit(): void {
var connection = new signalR.HubConnectionBuilder()
.withUrl("/center")
.build();
this.bindConnectionMessage(connection);
connection
.start()
.then(function () {
console.log("connection started");
})
.catch(function (error) {
console.error(error.message);
});
}
@ViewChild("mapContainer", { static: true }) gmap: ElementRef;
map: google.maps.Map;
lat = 40.73061;
lng = -73.935242;
coordinates = new google.maps.LatLng(this.lat, this.lng);
mapOptions: google.maps.MapOptions = {
center: this.coordinates,
zoom: 4,
};
ngAfterViewInit() {
this.mapInitializer();
}
mapInitializer() {
this.map = new google.maps.Map(this.gmap.nativeElement, this.mapOptions);
}
}
|
MegaMachine/project-x-server
|
src/app.service.ts
|
import { Injectable } from '@nestjs/common';
import { JwtService } from './auth/jwt/jwt.service';
import { env } from '../config/env';
import { IJwtHeader, IJwtPayload } from './auth/jwt/jwt.interface';
@Injectable()
export class AppService {
constructor(
private readonly jwtService: JwtService,
) {}
}
|
MegaMachine/project-x-server
|
src/auth/jwt/jwt.service.ts
|
import { Injectable } from '@nestjs/common';
import { IJwt, IJwtHeader, IJwtPayload } from './jwt.interface';
import * as crypto from 'crypto';
import { env } from '../../../config/env';
@Injectable()
export class JwtService {
private readonly iv: string = '1234567812345678';
createToken(header: IJwtHeader, payload: IJwtPayload, secretKey: string ): {token: string} {
const stringifyHeader = JSON.stringify(header);
const stringifyPayload = JSON.stringify(payload);
const unSignToken = this._createUnSingToken(stringifyHeader, stringifyPayload, header.alg);
const jwt: IJwt = {
header,
payload: this._getEncrypt(stringifyPayload, secretKey),
signature: this._getEncrypt(unSignToken, secretKey),
};
const stringifyJwt = JSON.stringify(jwt);
const hexJwt = Buffer.from(stringifyJwt, 'utf8')
.toString('hex');
return {token: hexJwt};
}
isTokenValid(externalJwt: string, secretKey: string): boolean {
try {
const token = externalJwt.split(' ');
const stringifyJwt = Buffer.from(token[1], 'hex').toString('utf8');
const internalJwt: IJwt = JSON.parse(stringifyJwt);
const decryptPayload = this._getDecrypt(internalJwt.payload, secretKey);
const stringifyHeader = JSON.stringify(internalJwt.header);
const createdUnSignToken = this._createUnSingToken(stringifyHeader, decryptPayload, internalJwt.header.alg);
const decryptedUnSignToken = this._getDecrypt(internalJwt.signature, secretKey);
if (createdUnSignToken === decryptedUnSignToken) {
return true;
}
} catch(err) {
console.log(err[`message`]);
}
return false;
}
getTokenPayload(externalJwt, secretKey) {
const token = externalJwt.split(' ');
const stringifyJwt = Buffer.from(token[1], 'hex').toString('utf8');
const internalJwt: IJwt = JSON.parse(stringifyJwt);
const decryptPayload = this._getDecrypt(internalJwt.payload, secretKey);
console.log(decryptPayload)
const parsePayload = JSON.parse(decryptPayload);
return parsePayload;
}
private _getHash(str: string, alg: string): string {
return crypto
.createHash(alg)
.update(str)
.digest('hex');
}
private _getEncrypt(str: string, secretKey: string): string {
const cipher = crypto.createCipheriv('aes-256-cbc', secretKey, this.iv);
let encrypt = cipher.update(str, 'utf8', 'hex');
return encrypt += cipher.final('hex');
}
private _getDecrypt(str: string, secretKey: string): string {
const decipher = crypto.createDecipheriv('aes-256-cbc', secretKey, this.iv);
let decrypted = decipher.update(str, 'hex', 'utf8');
return decrypted += decipher.final('utf8');
}
private _createUnSingToken(header: string, payload: string, alg: string): string {
return this._getHash(header, alg) + '.' + this._getHash(payload, alg);
}
}
|
MegaMachine/project-x-server
|
src/auth/auth.module.ts
|
<reponame>MegaMachine/project-x-server
import { Module } from '@nestjs/common';
import { JwtService } from './jwt/jwt.service';
// import { UserController } from './auth/auth.controller';
import { UserController } from '../user/user.controller';
import { DataBaseModule } from '../database/database.module';
import { UserService } from '../user/user.service';
import { CreateUserParser } from '../database/parser/create-user.parser';
// import { UserService } from './auth.service';
@Module({
imports: [],
providers: [JwtService],
exports: [JwtService],
controllers: [],
})
export class AuthModule { }
|
MegaMachine/project-x-server
|
src/middleware/auth.middleware.ts
|
import { NestMiddleware, Injectable } from '@nestjs/common';
import { Response, Request } from 'express';
import { env } from '../../config/env';
import { JwtService } from '../auth/jwt/jwt.service';
import { UserService } from '../user/user.service';
import { IRequest } from 'src/user/user.controller';
import { NextFunction } from 'connect';
@Injectable()
export class AuthMiddleware implements NestMiddleware {
constructor(
private jwtService: JwtService,
private userService: UserService,
) {}
async use(req: IRequest, res: Response, next: NextFunction) {
if (req.headers.authorization) {
next();
} else {
// res.redirect('http://localhost:3000/auth/sign-in');
res.sendStatus(401);
}
}
}
|
MegaMachine/project-x-server
|
src/interface/responce.interface.ts
|
<filename>src/interface/responce.interface.ts
export interface IResponseBody {
status: boolean;
data: any;
message: string;
error?: string;
}
|
MegaMachine/project-x-server
|
src/other/other.module.ts
|
import { Module } from "@nestjs/common";
import { OrmConfigService } from "./orm-config.service";
@Module({
providers: [OrmConfigService],
exports: [OrmConfigService],
})
export class OtherModule {}
|
MegaMachine/project-x-server
|
src/app.controller.ts
|
import { Controller, Get, Req, Param, Post, Body } from '@nestjs/common';
import { AppService } from './app.service';
import { Request } from 'express-serve-static-core';
import { IResponseBody } from './interface/responce.interface';
import { JwtService } from './auth/jwt/jwt.service';
import {env} from '../config/env'
@Controller()
export class AppController {
constructor(
private readonly jwtService: JwtService,
) { }
@Get()
getHello(
@Req() req: Request,
): IResponseBody {
const message = this.jwtService.isTokenValid(req.headers.authorization, env().secret)
? 'welcome'
: 'auth pls';
return {
status: true,
data: null,
message,
};
}
}
|
MegaMachine/project-x-server
|
src/user/user.service.ts
|
<gh_stars>0
import {
Injectable,
} from '@nestjs/common';
import {
DataBaseService,
IUser,
} from '../database/database.service';
import {
CreateUserParser,
} from '../database/parser/create-user.parser';
import {
JwtService,
} from '../auth/jwt/jwt.service';
import {
env,
} from '../../config/env';
import {
IJwtPayload,
IJwtHeader,
} from '../auth/jwt/jwt.interface';
import {
IResponseBody,
} from 'src/interface/responce.interface';
@Injectable()
export class UserService {
constructor(
private dataBaseService: DataBaseService,
private createUserParser: CreateUserParser,
private jwtService: JwtService,
) {}
async signUp(user: IUser): Promise < IResponseBody > {
try {
await this.dataBaseService.createUser(
this.createUserParser.parse(user),
);
return {
status: true,
data: null,
message: 'user was created',
};
} catch (err) {
if (err[`message`].indexOf('login_UNIQUE') !== -1) {
console.log(err[`message`]);
return {
status: false,
data: null,
message: 'this login exists'
};
}
if (err[`message`].indexOf('DATA_TOO_LONG') !== -1) {
console.log(err[`message`] + `. Length is: ${this.createUserParser.parse(user).password.length}`);
return {
status: false,
data: null,
message: 'long password',
};
}
}
}
async signIn(user: IUser): Promise < IResponseBody > {
const receivedUser: IUser = await this.dataBaseService.getUserByLogin(user.login);
if (receivedUser) {
const jwtHeader: IJwtHeader = {
alg: 'sha256',
typ: 'JWT',
};
const jwtPayload: IJwtPayload = {
id: receivedUser.id,
name: receivedUser.login,
};
if (this.createUserParser.verifyPassword(user.password, receivedUser.password)) {
console.log('Password correct');
console.log('Check Bearer', this.jwtService.createToken(jwtHeader, jwtPayload, env().secret))
return {
status: true,
data: this.jwtService.createToken(jwtHeader, jwtPayload, env().secret),
message: 'user was Login.',
};
} else {
console.log('Password incorrect');
return {
status: false,
data: null,
message: 'password or login incorrect',
};
}
} else {
return {
status: false,
data: null,
message: 'user not found',
};
}
}
async getUserInfo(id: string) {
return await this.dataBaseService.getUserById(id);
}
}
|
MegaMachine/project-x-server
|
src/app.module.ts
|
<reponame>MegaMachine/project-x-server<gh_stars>0
import { Module, NestModule, MiddlewareConsumer } from '@nestjs/common';
import { TypeOrmModule } from '@nestjs/typeorm';
import { AppController } from './app.controller';
import { AppService } from './app.service';
import { AuthModule } from './auth/auth.module';
import { AuthMiddleware } from './middleware/auth.middleware';
import * as dotenv from 'dotenv';
import { DBConfigService } from './database/db-config';
import { UserEntity } from './database/entity/user.entity';
import { OtherModule } from './other/other.module';
import { OrmConfigService } from './other/orm-config.service';
import { DataBaseModule } from './database/database.module';
import { UserModule } from './user/user.module';
import { UserController } from './user/user.controller';
dotenv.config();
@Module({
imports: [
TypeOrmModule.forRootAsync({
imports: [OtherModule],
useFactory: (ormConfigService: OrmConfigService) => {
return ormConfigService.getOrmConfig();
},
inject: [OrmConfigService],
}),
DataBaseModule,
UserModule,
AuthModule,
],
controllers: [AppController],
providers: [AppService],
})
export class AppModule implements NestModule {
configure(consumer: MiddlewareConsumer) {
consumer
.apply(AuthMiddleware)
.forRoutes(AppController);
}
}
|
MegaMachine/project-x-server
|
src/database/database.module.ts
|
import { Module } from "@nestjs/common";
import { DataBaseService } from "./database.service";
import { TypeOrmModule } from '@nestjs/typeorm';
import { UserEntity } from "./entity/user.entity";
import { CreateUserParser } from "./parser/create-user.parser";
@Module({
imports: [
TypeOrmModule.forFeature([UserEntity]),
],
providers: [
DataBaseService,
CreateUserParser,
],
exports: [DataBaseService, CreateUserParser],
})
export class DataBaseModule {}
|
MegaMachine/project-x-server
|
src/other/orm-config.service.ts
|
<filename>src/other/orm-config.service.ts<gh_stars>0
import { Injectable } from "@nestjs/common";
import * as path from 'path';
import 'dotenv/config';
@Injectable()
export class OrmConfigService {
getOrmConfig(): object {
return {
type: process.env.DB_TYPE,
host: process.env.DB_HOST,
port: process.env.DB_PORT,
username: process.env.DB_USER,
password: <PASSWORD>,
database: process.env.DB,
synchronize: false,
logging: false,
entities: [
`${path.dirname(require.main.filename)}/**/*.entity{.ts,.js}`,
],
};
}
}
|
MegaMachine/project-x-server
|
src/user/user.module.ts
|
<filename>src/user/user.module.ts
import { Module, NestModule, MiddlewareConsumer } from '@nestjs/common';
import { UserController } from '../user/user.controller';
import { DataBaseModule } from '../database/database.module';
import { UserService } from '../user/user.service';
import { AuthModule } from '../auth/auth.module';
import { UserMiddleware } from './user.middleware';
@Module({
imports: [DataBaseModule, AuthModule],
providers: [UserService],
controllers: [UserController],
exports: [UserService],
})
export class UserModule //{}
implements NestModule {
configure(consumer: MiddlewareConsumer) {
consumer
.apply(UserMiddleware)
.forRoutes(UserController);
}
}
|
MegaMachine/project-x-server
|
src/user/user.dto.ts
|
<filename>src/user/user.dto.ts
import { IsNotEmpty, IsString, Length } from 'class-validator';
export class UserDto {
@IsNotEmpty()
@IsString()
@Length(4, 16)
readonly login: string;
@IsNotEmpty()
@IsString()
@Length(4, 16)
readonly password: string;
}
|
MegaMachine/project-x-server
|
src/database/db-config.ts
|
<filename>src/database/db-config.ts
import { Injectable } from "@nestjs/common";
@Injectable()
export class DBConfigService {
private static readonly DB = process.env.DB;
private static readonly DB_HOST = process.env.DB_HOST;
private static readonly DB_PORT = process.env.DB_PORT;
private static readonly DB_USER = process.env.DB_USER;
private static readonly DB_PASSWORD = process.env.DB_PASSWORD;
private static readonly DB_TYPE = process.env.DB_TYPE;
static get getDataBase() {
return this.DB;
}
static get getDataBaseHost(): string {
return this.DB_HOST;
}
static get getDataBasePort(): number {
return parseFloat(this.DB_PORT);
}
static get getDataBaseUser(): string {
return this.DB_USER;
}
static get getDataBasePassword(): string {
return <PASSWORD>;
}
static get getDataBaseType(): string {
return this.DB_TYPE;
}
}
|
MegaMachine/project-x-server
|
config/env.ts
|
import * as dotenv from 'dotenv';
dotenv.config();
export function env() {
return {
secret: process.env.SECRET,
bearer: process.env.BEARER,
};
}
|
MegaMachine/project-x-server
|
src/database/database.service.ts
|
import { Injectable } from '@nestjs/common';
import { getConnection, getManager, getRepository, Repository } from 'typeorm';
import { UserEntity } from './entity/user.entity';
import { InjectRepository } from '@nestjs/typeorm';
export interface IUser {
id?: string;
login: string;
password: string;
}
@Injectable()
export class DataBaseService {
constructor(
@InjectRepository(UserEntity)
private userRepository: Repository<UserEntity>,
) {}
async createUser(user?: IUser) {
await getConnection()
.createQueryBuilder()
.insert()
.into('user')
.values([user])
.execute();
}
async getUserByLogin(login: string) {
return await this.userRepository
.createQueryBuilder('user')
.select()
.where('user.login = :value', { value: login })
.getOne();
}
async getUserById(id: string) {
console.log('getUserById', id)
return await this.userRepository.find({
where: {
id,
},
});
}
}
|
MegaMachine/project-x-server
|
src/user/user.controller.ts
|
<filename>src/user/user.controller.ts
import { Controller, Get, Req, Res, Post, Param, Body } from '@nestjs/common';
import { Request, Response } from 'express';
import { UserDto } from './user.dto';
import { UserService } from './user.service';
import { IResponseBody } from 'src/interface/responce.interface';
export interface IRequest extends Request{
user: object;
}
@Controller('user')
export class UserController {
constructor(
private userService: UserService,
) {}
@Post('/sign-up')
async createUser(
@Body() user: UserDto,
) {
console.log('Sign up user: ', user);
return await this.userService.signUp(user);
}
@Post('/sign-in')
async loginUser(
@Body() user: UserDto,
) {
console.log('Sign in user: ', user);
return await this.userService.signIn(user);
}
@Get('/me')
getUserInfo(
@Req() req: IRequest,
): IResponseBody {
console.log(req.user)
return {
status: true,
data: req.user,
message: 'user info',
};
}
}
|
MegaMachine/project-x-server
|
src/auth/jwt/jwt.interface.ts
|
export interface IJwt {
header: IJwtHeader;
payload: string;
signature: string;
}
export interface IJwtHeader {
alg: string;
typ: string;
}
export interface IJwtPayload {
id: string;
name: string;
}
|
MegaMachine/project-x-server
|
src/database/parser/create-user.parser.ts
|
import { UserDto } from '../../user/user.dto';
import { IUser } from '../database.service';
import * as uuid from 'uuid';
import * as crypto from 'crypto';
interface IUserPassword {
salt: string;
passwordHash: string;
}
export class CreateUserParser {
parse(user: UserDto): IUser {
const salt = '1231231231231231';
return {
login: user.login,
password: this._passwordHash(user.password, salt),
};
}
private _sha512(password, salt): string {
const hash = crypto.createHmac('sha256', salt);
hash.update(password);
const value = hash.digest('hex');
return value;
}
verifyPassword(passwordExternal: string, passwordInternal: string): boolean {
const utfPasswordInternalParse = Buffer.from(passwordInternal, 'hex').toString('utf8');
const passwordInternalParse: IUserPassword = JSON.parse(utfPasswordInternalParse);
const salt = passwordInternalParse.salt;
const passwordInternalHash = passwordInternalParse.passwordHash;
const passwordExternalHash = this._sha512(passwordExternal, salt);
let result: boolean;
passwordInternalHash === passwordExternalHash ? result = true : result = false;
return result;
}
private _passwordHash(password: string, salt: string): string {
const passwordHash = JSON.stringify({
salt,
passwordHash: this._sha512(password, salt),
});
const hexedPasswordHash = Buffer.from(passwordHash, 'utf8').toString('hex');
return hexedPasswordHash;
}
}
|
MegaMachine/project-x-server
|
src/user/user.middleware.ts
|
<reponame>MegaMachine/project-x-server<filename>src/user/user.middleware.ts
import { Injectable, NestMiddleware } from '@nestjs/common';
import { Request, Response } from 'express';
import { IRequest } from './user.controller';
import { JwtService } from '../auth/jwt/jwt.service';
import { UserService } from './user.service';
import { env } from '../../config/env';
@Injectable()
export class UserMiddleware implements NestMiddleware {
constructor(
private readonly jwtService: JwtService,
private readonly userService: UserService,
) {}
async use(req: IRequest, res: Response, next: () => void) {
if (req.headers.authorization) {
const payload = this.jwtService.getTokenPayload(req.headers.authorization, env().secret);
req.user = await this.userService.getUserInfo(payload.id);
console.log('User Middleware',req.user)
next();
}
next();
}
}
|
MegaMachine/project-x-server
|
src/database/entity/user.entity.ts
|
import { Entity, PrimaryColumn, PrimaryGeneratedColumn, BeforeInsert, Column } from 'typeorm';
import * as uuid from 'uuid';
@Entity('user')
export class UserEntity {
@PrimaryGeneratedColumn('uuid')
id: string;
@Column({ length: 45 })
login: string;
@Column({ length: 200 })
password: string;
@BeforeInsert()
generateID() {
this.id = uuid();
}
}
|
skylarvlalonde/Homestuck-Quirk-Generator
|
src/quirks/database/alternia/Kanaya.ts
|
import Quirk from "quirks/Quirk";
export default class Kanaya extends Quirk {
public constructor() {
super("<NAME>");
}
protected quirkify(): void {
const contractionMarks = "(\\b)['`](\\b)";
this.replaceString(contractionMarks, "$1$2");
const firstLetterOfWord = "\\b\\w";
this.upperCase(firstLetterOfWord);
}
}
|
skylarvlalonde/Homestuck-Quirk-Generator
|
src/quirks/collections/Hiveswap.ts
|
import Category from "quirks/Category";
import Daraya from "quirks/database/hiveswap/Daraya";
import Stelsa from "quirks/database/hiveswap/Stelsa";
import Kuprum from "quirks/database/hiveswap/Kuprum";
import Baizli from "quirks/database/hiveswap/Baizli";
import Remele from "quirks/database/hiveswap/Remele";
import Bronya from "quirks/database/hiveswap/Bronya";
import Karako from "quirks/database/hiveswap/Karako";
import Polypa from "quirks/database/hiveswap/Polypa";
import Tirona from "quirks/database/hiveswap/Tirona";
import Amisia from "quirks/database/hiveswap/Amisia";
import Lanque from "quirks/database/hiveswap/Lanque";
import Barzum from "quirks/database/hiveswap/Barzum";
import Xefros from "quirks/database/hiveswap/Xefros";
import Folykl from "quirks/database/hiveswap/Folykl";
import Ardata from "quirks/database/hiveswap/Ardata";
import Marsti from "quirks/database/hiveswap/Marsti";
import Azdaja from "quirks/database/hiveswap/Azdaja";
import Zebede from "quirks/database/hiveswap/Zebede";
import Fozzer from "quirks/database/hiveswap/Fozzer";
import Lynera from "quirks/database/hiveswap/Lynera";
import Boldir from "quirks/database/hiveswap/Boldir";
import Vikare from "quirks/database/hiveswap/Vikare";
import Nihkee from "quirks/database/hiveswap/Nihkee";
import Chixie from "quirks/database/hiveswap/Chixie";
import Chahut from "quirks/database/hiveswap/Chahut";
import Wanshi from "quirks/database/hiveswap/Wanshi";
import Mallek from "quirks/database/hiveswap/Mallek";
import Diemen from "quirks/database/hiveswap/Diemen";
import Trizza from "quirks/database/hiveswap/Trizza";
import Tagora from "quirks/database/hiveswap/Tagora";
import Tegiri from "quirks/database/hiveswap/Tegiri";
import Skylla from "quirks/database/hiveswap/Skylla";
import Zebruh from "quirks/database/hiveswap/Zebruh";
import Elwurd from "quirks/database/hiveswap/Elwurd";
import Tyzias from "quirks/database/hiveswap/Tyzias";
import Cirava from "quirks/database/hiveswap/Cirava";
import Marvus from "quirks/database/hiveswap/Marvus";
export default class Hiveswap extends Category {
public constructor() {
super("Hiveswap");
this.addQuirk(new Xefros());
this.addQuirk(new Trizza());
this.addQuirk(new Diemen());
this.addQuirk(new Ardata());
this.addQuirk(new Cirava());
this.addQuirk(new Amisia());
this.addQuirk(new Skylla());
this.addQuirk(new Bronya());
this.addQuirk(new Tagora());
this.addQuirk(new Vikare());
this.addQuirk(new Polypa());
this.addQuirk(new Zebruh());
this.addQuirk(new Elwurd());
this.addQuirk(new Kuprum());
this.addQuirk(new Folykl());
this.addQuirk(new Remele());
this.addQuirk(new Tyzias());
this.addQuirk(new Chixie());
this.addQuirk(new Azdaja());
this.addQuirk(new Chahut());
this.addQuirk(new Zebede());
this.addQuirk(new Tegiri());
this.addQuirk(new Mallek());
this.addQuirk(new Lynera());
this.addQuirk(new Tirona());
this.addQuirk(new Boldir());
this.addQuirk(new Stelsa());
this.addQuirk(new Marsti());
this.addQuirk(new Karako());
this.addQuirk(new Wanshi());
this.addQuirk(new Fozzer());
this.addQuirk(new Marvus());
this.addQuirk(new Daraya());
this.addQuirk(new Nihkee());
this.addQuirk(new Lanque());
this.addQuirk(new Barzum());
this.addQuirk(new Baizli());
}
}
|
skylarvlalonde/Homestuck-Quirk-Generator
|
src/quirks/database/hiveswap/Marvus.ts
|
<filename>src/quirks/database/hiveswap/Marvus.ts<gh_stars>1-10
import Quirk from "quirks/Quirk";
export default class Marvus extends Quirk {
public constructor() {
super("<NAME>");
}
protected quirkify(): void {
this.replaceEmotes("$1o$2");
}
}
|
darkusss/github-rest
|
src/pages/Profile.tsx
|
<filename>src/pages/Profile.tsx<gh_stars>0
import React, { useState } from 'react';
import { useParams, useSearchParams } from 'react-router-dom';
import ProfileView from '../components/ProfileView';
const Profile = () => {
const [searchParams, setSearchParams] = useSearchParams();
const [queryRepo, setQueryRepo] = useState<string>(searchParams.get('query') || '');
const handleQueryRepo = (repoName: string) => {
setQueryRepo(repoName);
setSearchParams({ query: repoName });
};
const params = useParams();
return (
<ProfileView
username={params.userId || ''}
queryRepo={queryRepo}
handleQueryRepo={handleQueryRepo}
/>
);
};
export default Profile;
|
darkusss/github-rest
|
src/components/ProfileView.tsx
|
<gh_stars>0
import React from 'react';
import ProfileDetails from './ProfileDetails';
import Search from './Search';
interface Props {
username: string;
queryRepo: string;
handleQueryRepo: (repoName: string) => void;
}
const ProfileView = ({ username, queryRepo, handleQueryRepo }: Props) => (
<div>
<Search query={queryRepo} handleQuery={handleQueryRepo} />
<ProfileDetails username={username} queryRepo={queryRepo} />
</div>
);
export default ProfileView;
|
darkusss/github-rest
|
src/layout/Footer.tsx
|
<reponame>darkusss/github-rest<gh_stars>0
import React from 'react';
import styles from '../scss/Footer.module.scss';
const Footer = () => (
<footer className={styles.footer}>
All rights are reserved. 2021
</footer>
);
export default Footer;
|
darkusss/github-rest
|
src/components/ProfilePreview.tsx
|
import React, { useState, useEffect, useContext } from 'react';
import { Link } from 'react-router-dom';
import UserContext from '../contexts/userContext';
import styles from '../scss/ProfilePreview.module.scss';
interface Props {
username: string;
}
const ProfilePreview = ({ username }: Props) => {
const [error, setError] = useState<string>('');
const { userData, setUserData } = useContext(UserContext);
useEffect(() => {
async function getGitHubUser() {
const response = await fetch(`${process.env.REACT_APP_GITHUB_API}${username}`);
try {
const data = await response.json();
if (data.message) {
setError(data.message);
} else {
if (setUserData) {
setUserData(data);
}
setError('');
}
} catch (incomeError: unknown) {
let errorMessage = 'Something unexpected happened. Try later';
if (incomeError instanceof Error) {
errorMessage = incomeError.message;
setError(errorMessage);
}
}
}
if (username) {
getGitHubUser();
}
}, [username]);
if (error) {
return (
<div className={styles.container}>
<span>{error}</span>
</div>
);
}
return (
<div className={styles.container}>
{!userData?.login
? <span>Hello!</span>
: (
<Link to={`profile/${username}`}>
<div>
<div>
<img
className={styles.avatar}
src={userData.avatar_url}
alt={`${userData.avatar_url} of ${userData.name}`}
/>
</div>
<div><h2>{userData.name || username}</h2></div>
<div>
Repos:
{' '}
{userData.public_repos}
</div>
</div>
</Link>
)}
</div>
);
};
export default ProfilePreview;
|
darkusss/github-rest
|
src/layout/Layout.tsx
|
<filename>src/layout/Layout.tsx
import React from 'react';
import { Outlet } from 'react-router-dom';
import Header from './Header';
import Footer from './Footer';
const Layout = () => (
<div>
<Header />
<Outlet />
<Footer />
</div>
);
export default Layout;
|
darkusss/github-rest
|
src/pages/Home.tsx
|
import React, { useState } from 'react';
import { useSearchParams } from 'react-router-dom';
import HomeView from '../components/HomeView';
const Home = () => {
const [searchParams, setSearchParams] = useSearchParams();
const [username, setUsername] = useState(searchParams.get('user') || '');
const handleUsername = (newUsername: string) => {
if (newUsername) {
setSearchParams({ user: newUsername });
setUsername(newUsername);
}
};
return (
<HomeView
searchQuery={username}
handleSearchQuery={handleUsername}
username={username}
/>
);
};
export default Home;
|
darkusss/github-rest
|
src/contexts/userContext.ts
|
<reponame>darkusss/github-rest<filename>src/contexts/userContext.ts
import React from 'react';
interface User {
userData?: Record<string, string>;
setUserData?: React.Dispatch<React.SetStateAction<Record<string, string>>>;
}
const UserContext = React.createContext<User>({});
export default UserContext;
|
darkusss/github-rest
|
src/components/Search.tsx
|
<reponame>darkusss/github-rest<filename>src/components/Search.tsx
import React, { useState, useEffect } from 'react';
interface Props {
query: string;
handleQuery: (searchQuery: string) => void;
}
const Search = ({ query, handleQuery }: Props) => {
const [searchQuery, setSearchQuery] = useState(query);
useEffect(() => {
const timeout = setTimeout(() => {
handleQuery(searchQuery);
}, 650);
return () => {
clearTimeout(timeout);
};
}, [searchQuery]);
const handleSearchQuery = (event: React.ChangeEvent<HTMLInputElement>) => {
setSearchQuery(event.target.value);
};
return (
<div>
<input value={searchQuery} onChange={handleSearchQuery} />
</div>
);
};
export default Search;
|
darkusss/github-rest
|
src/layout/Header.tsx
|
import React from 'react';
const Header = () => (
<header>
<h1>Github viewer</h1>
</header>
);
export default Header;
|
darkusss/github-rest
|
src/App.tsx
|
<gh_stars>0
import React, { useState, useMemo, useContext } from 'react';
import { Routes, Route, Navigate } from 'react-router-dom';
import Home from './pages/Home';
import Profile from './pages/Profile';
import UserContext from './contexts/userContext';
import styles from './scss/App.module.scss';
import Layout from './layout/Layout';
const RequireUser = ({ children }: { children: JSX.Element }) => {
const { userData } = useContext(UserContext);
if (!userData?.login) {
return <Navigate to="/" />;
}
return children;
};
const App = () => {
const [userData, setUserData] = useState({});
const contextValue = useMemo(() => ({ userData, setUserData }), [userData]);
return (
<UserContext.Provider value={contextValue}>
<div className={styles.App}>
<Routes>
<Route element={<Layout />}>
<Route path="/" element={<Home />} />
<Route
path="profile/:userId"
element={(
<RequireUser>
<Profile />
</RequireUser>
)}
/>
</Route>
</Routes>
</div>
</UserContext.Provider>
);
};
export default App;
|
darkusss/github-rest
|
src/components/ProfileDetails.tsx
|
<filename>src/components/ProfileDetails.tsx<gh_stars>0
import React, { useEffect, useState, useContext } from 'react';
import UserContext from '../contexts/userContext';
interface Props {
username: string;
queryRepo: string;
}
const filterRepos = (query: string, values: string[]) => (
values.some((value) => value?.includes(query))
);
const ProfileDetails = ({ username, queryRepo }: Props) => {
const [repos, setRepos] = useState<Array<Record<string, string>>>([]);
const [loading, setLoading] = useState(false);
const [error, setError] = useState('');
const { userData } = useContext(UserContext);
useEffect(() => {
async function getGitHubUserRepos() {
setLoading(true);
const response = await fetch(`${process.env.REACT_APP_GITHUB_API}${username}/repos?type=all&sort=updated&per_page=100`);
try {
const fetchedRepos = await response.json();
if (fetchedRepos.message) {
setError(fetchedRepos.message);
} else {
setRepos(fetchedRepos);
setError('');
}
} catch (incomeError: unknown) {
let errorMessage = 'Something unexpected happened. Try later';
if (incomeError instanceof Error) {
errorMessage = incomeError.message;
}
setError(errorMessage);
}
setLoading(false);
}
if (username) {
getGitHubUserRepos();
}
}, [username]);
if (error) {
return (
<div>
<span>{error}</span>
</div>
);
}
const renderRepos = repos?.reduce((prevRepos: Array<React.ReactNode>, currRepo) => {
if (queryRepo && !filterRepos(queryRepo, [currRepo.name, currRepo.description])) {
return prevRepos;
}
return prevRepos.concat((
<li key={currRepo.id}>
<div>
<a href={currRepo.html_url} target="_blank" rel="noreferrer noopener">
<h2>{currRepo.name}</h2>
<div>
<p>{currRepo.description}</p>
<h4>{currRepo.forks_count}</h4>
<h4>{currRepo.stargazers_count}</h4>
</div>
</a>
</div>
</li>
));
}, []);
return (
<div>
<div>
<div>
<img
src={userData?.avatar_url || ''}
alt={`${userData?.avatar_url} of ${userData?.name}`}
/>
</div>
<div>
<h2>{userData?.name || username}</h2>
<div>
<h3>{userData?.bio || 'No biography'}</h3>
<h4>
Followers
{' '}
{userData?.followers}
</h4>
<h4>
Following
{' '}
{userData?.following}
</h4>
<h5>{userData?.x}</h5>
<h5>
Join in
{' '}
{(userData?.created_at && new Date(userData.created_at).toDateString()) || 'never'}
</h5>
{userData?.email && <a href={`mailto:${userData.email}`}>{userData.email}</a>}
</div>
</div>
</div>
<div>
{loading ? <h3>Loading...</h3>
: (
<nav>
<ul>
{renderRepos}
</ul>
</nav>
)}
</div>
</div>
);
};
export default ProfileDetails;
|
darkusss/github-rest
|
src/components/HomeView.tsx
|
<gh_stars>0
import React from 'react';
import Search from './Search';
import ProfilePreview from './ProfilePreview';
interface Props {
searchQuery: string;
username: string;
handleSearchQuery: (searchQuery: string) => void;
}
const HomeView = ({ searchQuery, handleSearchQuery, username }: Props) => (
<div>
<Search query={searchQuery} handleQuery={handleSearchQuery} />
<ProfilePreview username={username} />
</div>
);
export default HomeView;
|
Brontoz554/nest-js-rework
|
src/user/user.service.ts
|
<filename>src/user/user.service.ts<gh_stars>0
import { Injectable } from '@nestjs/common';
import { InjectModel } from '@nestjs/mongoose';
import { User } from './schemas/user.schema';
import { CreateUserDto } from './dto/create-user.dto';
import { UpdateUserDto } from './dto/update-user.dto';
import { ExceptionsHandler } from '@nestjs/core/exceptions/exceptions-handler';
@Injectable()
export class UserService {
constructor(@InjectModel(User.name) private userModel) {
}
async getAll(): Promise<User[]> {
return this.userModel.find().populate('cart');
}
async getById(id: string): Promise<User> {
return this.userModel.findById(id);
}
async create(createUserDto: CreateUserDto): Promise<User | any> {
const newUser = new this.userModel(createUserDto);
try {
const user = await newUser.save();
return {
user: user,
message: 'Вы успешно зарегистрировались',
success: true,
};
// @ts-ignore
} catch (e: ExceptionsHandler) {
return {
user: e,
message: 'Что-то пошло не так',
success: false,
};
}
}
async removeUser(id: string): Promise<boolean> {
const object = await this.userModel.findByIdAndRemove(id);
if (object) {
return true;
} else {
return false;
}
}
async removeAll(): Promise<any> {
const objects = await this.userModel.find();
objects.forEach((item) => {
item.delete();
});
await this.getAll();
}
update(id: string, updateUserDto: UpdateUserDto): Promise<User> {
return this.userModel.findByIdAndUpdate(id, updateUserDto);
}
async addInCart(cart, cartId): Promise<any> {
const user = await this.userModel.findById(cart.user);
await user.cart.push(cartId);
return user.save();
}
}
|
Brontoz554/nest-js-rework
|
src/cart/cart.controller.ts
|
<gh_stars>0
import { Body, Controller, Delete, Get, Param, Post } from '@nestjs/common';
import { cartDto } from './dto/cart.dto';
import { CartService } from './cart.service';
import { Cart } from './schemas/cart.schema';
import { UserService } from '../user/user.service';
@Controller('cart')
export class CartController {
constructor(
readonly cartService: CartService,
readonly userService: UserService,
) {
}
/**
* Получить все корзины пользователей
*/
@Get()
async getAll(): Promise<Cart> {
return await this.cartService.getAll();
}
@Get('my-cart/:userId')
async getMyCart(@Param('userId') userId: string): Promise<Cart[]> {
return await this.cartService.getMyCart(userId);
}
/**
* Оформить покупку на все товары находящиеся в карзине пользователя
* @param userId
*/
@Get('buy-all/:userId')
async buyAll(@Param('userId') userId: string): Promise<string> {
return await this.cartService.buyAll(userId);
}
/**
* Оформить покупку на один конкретный товар, из корзины пользователя
* @param userId
* @param productId
*/
@Get('buy-one-product/:userId/:productId')
async buyProduct(@Param('userId') userId: string, @Param('productId') productId: string): Promise<any> {
return this.cartService.buyOneProduct(userId, productId);
}
/**
* Добавить товар в корзину
* @param cart
*/
@Post()
async addProductInCart(@Body() cart: cartDto): Promise<any> {
await this.cartService.addInCart(cart);
return 'Товар успешно добавлен в карзину';
}
/**
* Отчистить все корзины(для дебага)
*/
@Delete()
async removeAll(): Promise<string> {
await this.cartService.removeAll();
return 'Все корзины отчищены';
}
}
|
Brontoz554/nest-js-rework
|
src/products/products.controller.ts
|
<filename>src/products/products.controller.ts
import {
Controller,
Get,
Param,
Post,
Body,
Delete,
Put,
} from '@nestjs/common';
import { Product } from './schemas/product.schema';
import { CreateProductDto } from './dto/create-product-dto';
import { UpdateProductDto } from './dto/update-product-dto';
import { ProductsService } from './products.service';
import { CartService } from '../cart/cart.service';
import { ExceptionsHandler } from '@nestjs/core/exceptions/exceptions-handler';
@Controller('products')
export class ProductsController {
constructor(
private readonly productService: ProductsService,
private readonly cartService: CartService,
) {
}
@Get()
/**
* Получить все существующие товары
*/
getAll(): Promise<Product[]> {
return this.productService.getAll();
}
@Get(':id')
/**
* Получить информацию о товаре продукте по id
* @param id
*/
getOne(@Param('id') id: string): Promise<Product> {
return this.productService.getById(id);
}
@Post()
/**
* Создать новый товар
*/
async create(@Body() createProduct: CreateProductDto): Promise<Product | any> {
try {
const product = await this.productService.create(createProduct);
return {
product: product,
success: true,
};
// @ts-ignore
} catch (e: ExceptionsHandler) {
return {
message: e,
success: false,
};
}
}
@Put(':id')
/**
* Изменить характеристики товара
* @param productDto
* @param id
*/
update(
@Body() productDto: UpdateProductDto,
@Param('id') id: string,
): Promise<Product> {
return this.productService.update(id, productDto);
}
@Delete(':id')
/**
* Удалить товар
* @param id
*/
async remove(@Param('id') id: string) {
const status = await this.productService.remove(id);
if (status) {
return {
message: `Товар ${id} успешно удалён`,
success: true,
};
}
return {
message: 'Товар не найден',
success: false,
};
}
@Delete('delete-all')
/**
* Удалить все товары
*/
async deleteAll(): Promise<string> {
await this.cartService.removeAll();
// await this.productService.removeAll();
return 'Все товары удалены, а корзины пользователей отчищены';
}
}
|
Brontoz554/nest-js-rework
|
src/cart/cart.resolver.ts
|
import { Args, Mutation, Query, Resolver } from '@nestjs/graphql';
import { CartService } from './cart.service';
import { Cart } from './schemas/cart.schema';
import { cartDto } from './dto/cart.dto';
@Resolver()
export class CartResolver {
constructor(
readonly cartService: CartService,) {}
@Query(() => [Cart])
/**
* Получить все корзины пользователей
*/
getAllCarts(): Promise<Cart> {
return this.cartService.getAll();
}
@Query(() => [Cart])
/**
* Получить корзину пользователя по id
* @param userId
*/
getMyCart(@Args('userId') userId: string) {
return this.cartService.getMyCart(userId);
}
@Query(() => String)
/**
* Купить все продукты находящиеся в корзине пользователя
* @param userId
*/
buyAll(@Args('userId') userId: string) {
return this.cartService.buyAll(userId);
}
@Query(() => String)
/**
* Купить продукт находящийся в корзине
* @param userId
* @param productId
*/
buyProduct(@Args('userId') userId: string, @Args('productId') productId: string) {
return this.cartService.buyOneProduct(userId, productId);
}
@Mutation(() => [Cart])
/**
* Добавить продукт в корзину
*/
async addProductInCart(@Args('cartDto') CartDto: cartDto) {
await this.cartService.addInCart(CartDto);
return this.getMyCart(CartDto.user);
}
@Query(() => [Cart])
/**
* Отчистить все корзины пользователей.
*/
async removeAllCarts() {
await this.cartService.removeAll();
return this.getAllCarts();
}
}
|
Brontoz554/nest-js-rework
|
src/user/dto/create-user.dto.ts
|
<filename>src/user/dto/create-user.dto.ts
import { IsNotEmpty, IsString, MaxLength, MinLength } from 'class-validator';
import { Field, InputType, ObjectType } from '@nestjs/graphql';
@InputType()
@ObjectType()
export class CreateUserDto {
@IsNotEmpty()
@IsString()
@MinLength(5)
@MaxLength(10)
@Field()
readonly firstName: string;
@IsNotEmpty()
@IsString()
@Field()
readonly secondName: string;
@IsNotEmpty()
@IsString()
@MinLength(11) // 8 999
@MaxLength(12) // +7 999
@Field()
readonly phone: string;
@IsNotEmpty()
@IsString()
@Field()
readonly password: string;
}
|
Brontoz554/nest-js-rework
|
src/user/user.controller.ts
|
import {
Body,
Controller,
Delete,
Get,
Param,
Post,
Put,
} from '@nestjs/common';
import { UserService } from './user.service';
import { User } from './schemas/user.schema';
import { CreateUserDto } from './dto/create-user.dto';
import { UpdateUserDto } from './dto/update-user.dto';
import { CartService } from '../cart/cart.service';
import * as mongoose from 'mongoose';
@Controller('user')
export class UserController {
constructor(
private readonly userService: UserService,
private readonly cartService: CartService) {
}
@Get()
/**
* Получить всех юзеров
*/
getAll(): Promise<User[]> {
return this.userService.getAll();
}
@Get(':id')
/**
* Получить конкретного юзера по id
* @param id
*/
getUserById(@Param('id') id: string): Promise<User> {
return this.userService.getById(id);
}
@Post()
/**
* Создание нового юзера
*/
createUser(@Body() createUser: CreateUserDto): Promise<object | unknown> {
return this.userService.create(createUser);
}
@Put(':id')
/**
* Изменение данных пользователя
* @param createUser
* @param id
*/
update(@Body() createUser: UpdateUserDto, @Param('id') id: string) {
return this.userService.update(id, createUser);
}
@Delete('delete-all-users')
/**
* Удалить всех юзеров
*/
removeAllUsers() {
return this.userService.removeAll();
}
@Delete(':id')
/**
* Удалить конкретного юзера
* @param id
*/
async removeUser(@Param('id') id: string): Promise<object> {
await this.cartService.removeUserCart(id);
const status = await this.userService.removeUser(id);
if (status) {
return {
message: `пользователь ${id} успешно удалён`,
success: true,
};
}
return {
message: 'пользователь не найден',
success: false,
};
}
}
|
Brontoz554/nest-js-rework
|
src/products/products.resolver.ts
|
import { Args, Mutation, Query, Resolver } from '@nestjs/graphql';
import { ProductsService } from './products.service';
import { CreateProductDto } from './dto/create-product-dto';
import { Product } from './schemas/product.schema';
import { UpdateProductDto } from './dto/update-product-dto';
import { CartService } from '../cart/cart.service';
@Resolver()
export class ProductsResolver {
constructor(
private readonly productsService: ProductsService,
private readonly cartService: CartService,
) {
}
@Query(() => [Product])
/**
* Получить все товары
*/
getAllProducts(): Promise<Product[]> {
return this.productsService.getAll();
}
@Query(() => Product)
/**
* Получить конкретный товар
* @param id
*/
getProduct(@Args('id') id: string): Promise<Product> {
return this.productsService.getById(id);
}
@Mutation(() => Product)
/**
* Добавить новый продукты
* @param createProduct
*/
addProduct(@Args('createProduct') createProduct: CreateProductDto): Promise<Product> {
return this.productsService.create(createProduct);
}
@Mutation(() => Product)
/**
* Удалить продукт
* @param id
*/
removeProduct(@Args('id') id: string) {
return this.productsService.remove(id);
}
@Mutation(() => Product)
/**
* Изменить описание продукта
* @param id
* @param productDto
*/
updateProduct(
@Args('id') id: string,
@Args('updateProduct') productDto: UpdateProductDto,
) {
return this.productsService.update(id, productDto);
}
@Query(() => Product)
/**
* Удалить все продукты
*/
async removeAllProduct() {
await this.cartService.removeAll();
await this.productsService.removeAll();
return this.getAllProducts();
}
}
|
Brontoz554/nest-js-rework
|
src/products/dto/update-product-dto.ts
|
import { IsNumber, IsOptional, IsString, MaxLength, MinLength } from 'class-validator';
import { Field, InputType, ObjectType } from '@nestjs/graphql';
@InputType()
@ObjectType()
export class UpdateProductDto {
@IsString()
@MinLength(1)
@MaxLength(50)
@IsOptional()
@Field()
readonly title: string;
@IsNumber()
@IsOptional()
@Field()
readonly price: number;
}
|
Brontoz554/nest-js-rework
|
src/user/user.resolver.ts
|
<gh_stars>0
import { Args, Mutation, Query, Resolver } from '@nestjs/graphql';
import { UserService } from './user.service';
import { CartService } from '../cart/cart.service';
import { User } from './schemas/user.schema';
import { CreateUserDto } from './dto/create-user.dto';
import { UpdateUserDto } from './dto/update-user.dto';
@Resolver()
export class UserResolver {
constructor(
private readonly userService: UserService,
private readonly cartService: CartService,
) {
}
@Query(() => [User])
/**
* Получить данные всех юзеров
*/
getAllUser() {
return this.userService.getAll();
}
@Query(() => User)
/**
* Получить данные юзера по id
* @param userId
*/
getUser(@Args('userId') userId: string) {
return this.userService.getById(userId);
}
@Query(() => User)
/**
* Удалить данные пользователя
*/
async deleteUser(@Args('id') id: string) {
await this.cartService.removeUserCart(id);
await this.userService.removeUser(id);
return this.getUser(id);
}
@Query(() => [User])
/**
* Удалить всех пользователей и отчистить их корзины
*/
async deleteAllUsers() {
await this.userService.removeAll();
await this.cartService.removeAll();
return this.getAllUser();
}
@Mutation(() => User)
/**
* Добавить нового пользователя
*/
async createUser(@Args('user') user: CreateUserDto) {
const newUser = await this.userService.create(user);
return newUser.user;
}
@Mutation(() => User)
/**
* Изменить данные пользователя
* @param id
* @param user
*/
updateUser(@Args('id') id: string, @Args('updateUser') user: UpdateUserDto) {
return this.userService.update(id, user);
}
}
|
Brontoz554/nest-js-rework
|
src/cart/schemas/cart.schema.ts
|
<gh_stars>0
import { Prop, Schema, SchemaFactory } from '@nestjs/mongoose';
import * as mongoose from 'mongoose';
import { Product } from '../../products/schemas/product.schema';
import { Field, ID, ObjectType } from '@nestjs/graphql';
@ObjectType()
@Schema()
export class Cart {
@Field(() => ID)
_id: string;
@Field(() => String)
@Prop()
user: string;
@Field(() => Product)
@Prop({ type: mongoose.Schema.Types.ObjectId, ref: 'Product' })
product: Product;
@Field(() => Number)
@Prop()
count: number;
@Field(() => Number)
@Prop()
price: number;
}
export const CartSchema = SchemaFactory.createForClass(Cart);
|
Brontoz554/nest-js-rework
|
src/user/schemas/user.schema.ts
|
<gh_stars>0
import { Prop, Schema, SchemaFactory } from '@nestjs/mongoose';
import * as mongoose from 'mongoose';
import { Cart } from '../../cart/schemas/cart.schema';
import { Field, ID, ObjectType } from '@nestjs/graphql';
@ObjectType()
@Schema()
export class User {
@Field(() => ID, { nullable: true })
_id: string;
@Field(() => String, { nullable: true })
@Prop({ type: String })
firstName: string;
@Field(() => String, { nullable: true })
@Prop({ type: String })
secondName: string;
@Field(() => String, { nullable: true })
@Prop({ type: String, unique: true })
phone: string;
@Field(() => String, { nullable: true })
@Prop({ type: String })
password: string;
}
export const UserSchema = SchemaFactory.createForClass(User);
|
Brontoz554/nest-js-rework
|
src/products/products.service.ts
|
<filename>src/products/products.service.ts
import { Injectable } from '@nestjs/common';
import { InjectModel } from '@nestjs/mongoose';
import { Model } from 'mongoose';
import { CreateProductDto } from './dto/create-product-dto';
import { Product, ProductDocument } from './schemas/product.schema';
import { UpdateProductDto } from './dto/update-product-dto';
@Injectable()
export class ProductsService {
constructor(
@InjectModel(Product.name) private productModel: Model<ProductDocument>,
) {
}
async getAll(): Promise<Product[]> {
return this.productModel.find();
}
async getById(id: string): Promise<Product> {
return this.productModel.findById(id);
}
async getByTitle(title: string) {
return this.productModel.find({ title: { $eq: title } });
}
async create(productDto: CreateProductDto): Promise<Product> {
const newProduct = new this.productModel(productDto);
return newProduct.save();
}
async remove(id: string): Promise<boolean> {
const object = await this.productModel.findByIdAndRemove(id);
if (object) {
return true;
} else {
return false;
}
}
async removeAll() {
const objects = await this.productModel.find().exec();
if (objects.length != 0) {
objects.forEach((item) => {
item.delete();
});
}
}
async update(id: string, productDto: UpdateProductDto): Promise<Product> {
return this.productModel.findByIdAndUpdate(id, productDto, { new: true });
}
}
|
Brontoz554/nest-js-rework
|
src/cart/dto/cart.dto.ts
|
<gh_stars>0
import { IsNotEmpty, IsNumber, IsOptional, Max, Min } from 'class-validator';
import { Field, ID, InputType, ObjectType } from '@nestjs/graphql';
import { Product } from '../../products/schemas/product.schema';
import { User } from '../../user/schemas/user.schema';
@InputType()
@ObjectType()
export class cartDto {
@Field(() => ID, { nullable: true })
readonly _id?: string;
@IsNotEmpty()
@Field(() => String)
readonly user: string;
@IsNotEmpty()
@Field(() => String)
readonly product: string;
@IsNumber()
@Min(1)
@Max(10)
@IsOptional()
@Field(() => Number)
count: number;
}
|
Brontoz554/nest-js-rework
|
src/user/user.module.ts
|
<filename>src/user/user.module.ts
import { Module } from '@nestjs/common';
import { MongooseModule } from '@nestjs/mongoose';
import { UserService } from './user.service';
import { UserController } from './user.controller';
import { CartService } from '../cart/cart.service';
import { User, UserSchema } from './schemas/user.schema';
import { Cart, CartSchema } from '../cart/schemas/cart.schema';
import { Product, ProductSchema } from '../products/schemas/product.schema';
import { UserResolver } from './user.resolver';
@Module({
providers: [UserService, CartService, UserResolver],
controllers: [UserController],
imports: [
MongooseModule.forFeature([
{ name: Cart.name, schema: CartSchema },
{ name: User.name, schema: UserSchema },
{ name: Product.name, schema: ProductSchema },
]),
],
})
export class UserModule {
}
|
Brontoz554/nest-js-rework
|
src/products/dto/create-product-dto.ts
|
<filename>src/products/dto/create-product-dto.ts
import {
IsNotEmpty,
IsNumber,
IsString,
MaxLength,
MinLength,
} from 'class-validator';
import { Field, ID, InputType, ObjectType } from '@nestjs/graphql';
@InputType()
@ObjectType()
export class CreateProductDto {
@Field(() => ID, { nullable: true })
_id: string;
@IsNotEmpty()
@IsString()
@MinLength(1)
@MaxLength(50)
@Field({ nullable: true })
readonly title: string;
@IsNotEmpty()
@IsNumber()
@Field({ nullable: true })
readonly price: number;
}
|
Brontoz554/nest-js-rework
|
src/cart/cart.service.ts
|
<filename>src/cart/cart.service.ts<gh_stars>0
import { Injectable } from '@nestjs/common';
import { InjectModel } from '@nestjs/mongoose';
import { Cart } from './schemas/cart.schema';
import { cartDto } from './dto/cart.dto';
@Injectable()
export class CartService {
constructor(@InjectModel(Cart.name) private cartModel) {
}
/**
* метод добавляющий товар в корзину
* @param cart
*/
async addInCart(cart: cartDto): Promise<any> {
const cartRecord = await this.cartModel.findOne({
$and: [
{ user: { $eq: cart.user } },
{ product: { $eq: cart.product } },
],
});
if (!cartRecord) {
const cartRecord = await new this.cartModel(cart).save();
return cartRecord._id;
} else {
cartRecord.count += cart.count;
cartRecord.save();
}
return cartRecord._id;
}
/**
* Метод получающий все корзины пользователей
*/
async getAll(): Promise<Cart> {
return this.cartModel.find().populate('product');
}
/**
* Отчищает все корзины пользователей
*/
async removeAll(): Promise<any> {
const objects = await this.cartModel.find().exec();
if (objects.length != 0) {
await this.removeObjects(objects);
}
}
/**
* Купить все товары находящиеся в корзине пользователя
* @param userId
*/
async buyAll(userId): Promise<string> {
const cart = await this.cartModel.find({ user: userId }).populate('product');
if (cart.length == 0) {
return 'Ваша корзина пуста';
}
const totalPrice = await this.getProductsPrice(cart);
await this.removeObjects(cart);
return `Вы успешно оформили покупку на сумму ${totalPrice}`;
}
/**
* Получить сумму товаров, которые находятся в получаемой колекции
* @param cart
*/
async getProductsPrice(cart): Promise<number> {
let price = 0;
cart.forEach((item) => {
price += item.count * item.product.price;
});
return price;
}
/**
* Удаляет из корзины один продукт или удаляет всю запись, если count = 0
* @param userId
* @param productId
*/
async buyOneProduct(userId, productId): Promise<any> {
const product = await this.cartModel.findOne({
$and: [
{ user: { $eq: userId } },
{ product: { $eq: productId } },
],
}).populate('product');
if (product) {
product.count--;
product.count === 0
? product.delete()
: product.save();
} else {
return 'Корзина пуста';
}
return `Вы успешно оформили покупку ${product.product.title} на сумму ${product.product.price}`;
}
/**
* Получить товары находящиеся в корзине пользователя
* @param userId
*/
async getMyCart(userId): Promise<Cart[]> {
return await this.cartModel.find({ user: userId }).populate('product');
}
/**
* Отчистить корзину пользователя
* @param id
*/
async removeUserCart(id) {
const userCart = await this.cartModel.find({ user: id }).exec();
await this.removeObjects(userCart);
}
/**
* Вспомогательный метод, удаляющий все записи которые находятся в получаемой коллекции
* @param objects
*/
async removeObjects(objects) {
objects.forEach((item) => {
item.delete();
});
}
}
|
sudarshan-1708/UserManagementAPI
|
cypress/integration/appTest.spec.ts
|
describe('testing API endPoints', ()=>{
// it('it should return users from database',()=>{
// cy.request('http:localhost:3000/users/1').then((res)=>{
// expect(res.body).has.property('firstName','Sudarshan')
// })
// });
it('should authenticate the user if user is valid',()=>{
cy.login('Sudarshan','shukla@123')
})
it('should get users data present in database',()=>{
cy.getUsers();
})
it('get Users details via ID',()=>{
cy.getUserById('1')
})
// it('should add new user to data base',()=>{
// cy.addUser('Pranjal','Dubey','<EMAIL>',91976576871,'Varanshi','UP','India','ppNotSecure')
// })
it('update Users details via ID',()=>{
cy.updateById('2','Raja','Babu')
})
it('should delete the user by Id',()=>{
cy.deleteUser('2')
})
})
|
sudarshan-1708/UserManagementAPI
|
src/users/users.controller.ts
|
<reponame>sudarshan-1708/UserManagementAPI<gh_stars>0
import { Body, Controller, Delete, Get, Param, ParseIntPipe, Post, Put, UseGuards } from '@nestjs/common';
import { AuthGuard } from '@nestjs/passport';
import { ApiBearerAuth, ApiCreatedResponse, ApiOkResponse, ApiOperation, ApiResponseProperty, ApiTags } from '@nestjs/swagger';
import { JwtAuthGuard } from 'src/auth/jwt-auth.guard';
import { Public } from './customDecorator/publicAuth.decorator';
import { UserDto } from './dto/user.dto';
import { User } from './entity/user.entity';
import { UsersService } from './users.service';
@ApiTags('Users')
@Controller('users')
export class UsersController {
constructor(private userService : UsersService) {}
/**
* @description Route: http:localhost:3000/users. Gets all the users information present in the database
* @returns [userName:string,lastname:string,emailId:string,phoneNumber:number,city:string,state:string,country:string,password:string]
* @example {
* id: 1,firstName: Sudarshan, lastName:Shukla, emailId:<EMAIL>, phoneNumber: 9369426294, city:Pratapgarh,state:Uttar Pradesh, country:India,password:<PASSWORD>
* }
*/
@UseGuards(AuthGuard('jwt'))
@ApiOperation({summary:'Gets all user data present in DataBase'})
@ApiOkResponse({type:User, isArray: true, description :'Fetch all users present in DataBase'})
@Get()
@ApiBearerAuth()
getUsers(): Promise<User[]> {
return this.userService.getAll();
}
/**
* @description Route (GET) users/{:id}. Gives the user date with given user Id.
* @param id
* @returns [id:number,userName:string,lastname:string,emailId:string,phoneNumber:number,city:string,state:string,country:string,password:string]
* @example http://localhost:3000/user/1
* {
* id: 1,firstName: Sudarshan, lastName:Shukla, emailId:<EMAIL>, phoneNumber: 9369426294, city:Pratapgarh,state:Uttar Pradesh, country:India,password:<PASSWORD>
* }
*/
@UseGuards(AuthGuard('jwt'))
@ApiOperation({summary:'Get User information by their id',parameters:[]})
@ApiOkResponse({type:User, description:'Get user information respective to their id'})
@Get(':id')
@ApiBearerAuth()
getUserById(@Param('id', ParseIntPipe) id:number){
return this.userService.getOneById(id);
}
/**
* @description Route: localhost:3000/users , Request: POST
* @requires Requires user DTO --> [firstName:string, lastName:string, emailId:string, phoneNumber:number, city:string, state:string, country:string, password:string]]
* @description Adds a new User in DataBase, Takes UserDto (*given in param section)
* @param UserDTO : Defines the data trafer object's property to flow on network --> [firstName:string, lastName:string, emailId:string, phoneNumber:number, city:string, state:string, country:string, password:string]
* @return UserEnitity with: [firstname,lastName,emailId,city,state,country,password --> String , phoneNumber -->number and self-generatedId --> number ]
* @example {
* firstName: "Sudarshan", lastName:"Shukla", emailId:"<EMAIL>", phoneNumber: 9369426294, city:"Pratapgarh",state:"Uttar Pradesh", country:"India",password:"<PASSWORD>"
* }
*/
@UseGuards(AuthGuard('jwt'))
@ApiCreatedResponse({type : User, description:'Add new user to DataBase with respective DTO and autoIncrementing ID'})
@ApiOperation({summary:'Add user to dataBase with described DTO as references below in schema section'})
@Post()
@ApiBearerAuth()
create(@Body() userDto: UserDto) {
return this.userService.createUser(userDto);
}
/**
* @description Route: (@PUT) user/1 . Update user information on respective userId according to given information on DTO properties
* @param id User id -> where we have to update user information
* @param user userDto -> to update user properties on database
* @returns UserEnitity with: [id:number,firstname,lastName,emailId,city,state,country,password --> String , phoneNumber -->number and self-generatedId --> number ]
* @example http://localhost:3000/user/1
* {
* id: 1,firstName: Sudarshan, lastName:Shukla, emailId:<EMAIL>, phoneNumber: 9369426294, city:Pratapgarh,state:Uttar Pradesh, country:India,password:<PASSWORD>
* }
*/
@UseGuards(AuthGuard('jwt'))
@ApiCreatedResponse({type:User, description:'Update user with respective Id'})
@ApiOperation({summary:"Update user by providing user's Id and information as per DTO properties. Information will be updated on respected user id."})
@Put(':id')
@ApiBearerAuth()
update(@Param('id', ParseIntPipe) id: number, @Body() user: UserDto) {
return this.userService.updateInfoOfUser(id,user);
}
/**
* @description Route: (Delete) users. Removes user from the dataBase with given Id
* @param id
*/
@UseGuards(AuthGuard('jwt'))
@ApiCreatedResponse({type:User, description:'Remove user with respective Id'})
@ApiOperation({summary:'Delete user form database with respective user id.'})
@Delete(':id')
@ApiBearerAuth()
delete(@Param('id', ParseIntPipe) id: number){
return this.userService.deleteOneUser(id);
}
}
|
sudarshan-1708/UserManagementAPI
|
src/users/entity/user.entity.ts
|
import { ApiProperty } from "@nestjs/swagger";
import { Column, Entity, PrimaryGeneratedColumn } from "typeorm";
@Entity()
export class User{
@ApiProperty()
@PrimaryGeneratedColumn()
id : number;
@ApiProperty()
@Column()
firstName : string;
@ApiProperty()
@Column()
lastName : string;
@ApiProperty()
@Column()
emailId : string;
@ApiProperty()
@Column()
phoneNumber : number;
@ApiProperty()
@Column()
city : string;
@ApiProperty()
@Column()
state : string;
@ApiProperty()
@Column()
country : string;
@ApiProperty()
@Column()
password : string;
}
|
sudarshan-1708/UserManagementAPI
|
src/users/dto/user.dto.ts
|
<reponame>sudarshan-1708/UserManagementAPI
import { ApiProperty } from "@nestjs/swagger";
import { IsEmail, IsNumber, IsString } from "class-validator";
export class UserDto{
@ApiProperty()
@IsString()
firstName : string;
@ApiProperty()
@IsString()
lastName : string;
@ApiProperty({"required":false})
@IsEmail()
emailId : string;
@ApiProperty()
@IsNumber()
phoneNumber : number;
@ApiProperty()
@IsString()
city : string;
@ApiProperty()
@IsString()
state : string;
@ApiProperty()
@IsString()
country : string;
@ApiProperty()
@IsString()
password : string;
}
|
sudarshan-1708/UserManagementAPI
|
src/users/users.controller.spec.ts
|
<reponame>sudarshan-1708/UserManagementAPI
import { Test, TestingModule } from '@nestjs/testing';
import { UsersController } from './users.controller';
import { UsersService } from './users.service';
describe('UsersController', () => {
let controller: UsersController;
const mockUserService = {
createUser: jest.fn(dto => {
return {
id : Date.now(),
...dto
}
}),
updateInfoOfUser: jest.fn().mockImplementation((id,dto) => ({
id,
...dto
})),
deleteOneUser : jest.fn(id => {
return 'User deleted'
}),
getAll : jest.fn(()=>{
return 'All user details';
}),
getOneById : jest.fn(id =>{
return 'Single user details with respective id'
})
}
beforeEach(async () => {
const module: TestingModule = await Test.createTestingModule({
controllers: [UsersController],
providers : [UsersService],
}).overrideProvider(UsersService).useValue(mockUserService).compile();
controller = module.get<UsersController>(UsersController);
});
it('should be defined', () => {
expect(controller).toBeDefined();
})
it('should create a new user', () =>{
expect(controller.create({firstName : 'Sudarshan',
lastName : 'Shukla',
emailId : '<EMAIL>',
phoneNumber : 9889057397,
city : 'Pratapgarh',
state : 'UP',
country : 'India',
password : '<PASSWORD>'})).toEqual({
id : expect.any(Number),
firstName : 'Sudarshan',
lastName : 'Shukla',
emailId : '<EMAIL>',
phoneNumber : 9889057397,
city : 'Pratapgarh',
state : 'UP',
country : 'India',
password : '<PASSWORD>'
});
})
it('should update user information', () =>{
const dto = {firstName : 'Sudarshan',
lastName : 'Shukla',
emailId : '<EMAIL>',
phoneNumber : 9889057397,
city : 'Pratapgarh',
state : 'UP',
country : 'India',
password : <PASSWORD>'}
expect(controller.update(1,dto)).toEqual({
id:1,
...dto
})
});
it('should delete a user', () => {
expect(controller.delete(1)).toBe('User deleted')
})
it('should get all user information', () =>{
expect(controller.getUsers()).toEqual('All user details')
})
it('should fetch one user respective to user id', () =>{
expect(controller.getUserById(1)).toBe("Single user details with respective id")
})
});
|
sudarshan-1708/UserManagementAPI
|
src/app.service.ts
|
<gh_stars>0
import { Injectable } from '@nestjs/common';
import { AuthService } from './auth/auth.service';
@Injectable()
export class AppService {
constructor(private authService:AuthService) {}
}
|
sudarshan-1708/UserManagementAPI
|
src/users/users.service.ts
|
<reponame>sudarshan-1708/UserManagementAPI
import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { UserDto } from './dto/user.dto';
import { User } from './entity/user.entity';
//export type user = User;
@Injectable()
export class UsersService {
constructor(@InjectRepository(User) private usersRepository: Repository<User>) {}
// Authenticastion Logic : Start
async findOne(username: string): Promise<User | undefined> {
// return this.usersRepository.findOneOrFail(username);
return this.usersRepository.findOne({firstName:username});
}
// Authentication logic : End
getAll():Promise<User[]> {
return this.usersRepository.find(); // SELECT * FROM user
}
async getOneById(id: number) : Promise<User> {
try{
const user = await this.usersRepository.findOneOrFail(id);
return user;
}catch(err){
throw err;
};
}
createUser(user:UserDto): Promise<User>{
const newUser = this.usersRepository.create(user);
return this.usersRepository.save(newUser);
}
async updateInfoOfUser(id:number, user:UserDto) : Promise<User> {
const updateUser = await this.getOneById(id);
updateUser.city = user.city;
updateUser.state = user.state;
updateUser.country = user.country;
updateUser.emailId = user.emailId;
updateUser.firstName = user.firstName;
updateUser.lastName = user.lastName;
updateUser.password = <PASSWORD>;
updateUser.phoneNumber = user.phoneNumber;
return this.usersRepository.save(updateUser);
}
async deleteOneUser(id:number) : Promise<User>{
const deleteUser = await this.getOneById(id);
return this.usersRepository.remove(deleteUser);
}
}
|
sudarshan-1708/UserManagementAPI
|
src/app.controller.ts
|
import { Body, Controller, Delete, Get, Post, Request, Response, UseGuards } from '@nestjs/common';
import { ApiBearerAuth, ApiOkResponse, ApiOperation, ApiTags } from '@nestjs/swagger';
import { AppService } from './app.service';
import { AuthService } from './auth/auth.service';
import { AuthDto } from './auth/dto/AuthDto.dto';
import { JwtAuthGuard } from './auth/jwt-auth.guard';
import { LocalAuthGuard } from './auth/local-auth.guard';
var token;
@Controller()
export class AppController {
constructor(
private readonly appService: AppService,
private authService:AuthService
) {}
@ApiTags("Authentication")
@UseGuards(LocalAuthGuard)
@ApiOperation({summary:'Create JWT token for authentication by providing: username and password as JSON object.'})
@ApiOkResponse({ description:'Returns JWT token for endpoints authorization.'})
@Post('auth/login')
async login(@Body() authDto:AuthDto,@Request() req){
token = this.authService.login(req.user);
return token;
}
@ApiTags("Authentication")
@UseGuards(JwtAuthGuard)
@ApiOperation({summary:'Get User information on authorised token'})
@ApiOkResponse({description:'Gives JWT token information '})
@Get('profile')
@ApiBearerAuth()
getProfile(@Request() req): any{
return req.user;
}
}
|
sudarshan-1708/UserManagementAPI
|
src/users/db/migrations/1636340895828-UserMigration.ts
|
import {MigrationInterface, QueryRunner} from "typeorm";
export class UserMigration1636340895828 implements MigrationInterface {
name = 'UserMigration1636340895828'
public async up(queryRunner: QueryRunner): Promise<void> {
await queryRunner.query(`CREATE TABLE "user" ("id" integer PRIMARY KEY AUTOINCREMENT NOT NULL, "firstName" varchar NOT NULL, "lastName" varchar NOT NULL, "emailId" varchar NOT NULL, "phoneNumber" integer NOT NULL, "city" varchar NOT NULL, "state" varchar NOT NULL, "country" varchar NOT NULL, "password" varchar NOT NULL)`);
}
public async down(queryRunner: QueryRunner): Promise<void> {
await queryRunner.query(`DROP TABLE "user"`);
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.