Function bodies 59 total
render function · javascript · L10-L26 (17 LOC)src/client/app.jsx
function render() {
const preloadedState = window.__PRELOADED_STATE__;
delete window.__PRELOADED_STATE__;
const store = createStore(preloadedState);
hydrateRoot(
document.getElementById('root'),
<React.StrictMode>
<BrowserRouter>
<Provider store={store}>
<Router />
</Provider>
</BrowserRouter>
</React.StrictMode>
);
}generateRequest function · javascript · L31-L40 (10 LOC)src/client/redux/actions.js
export function generateRequest({ body, ...options }) {
return {
[RSAA]: {
method: 'GET',
headers: { 'Content-Type': 'application/json' },
body: body && JSON.stringify(body),
...options,
},
};
}postsReducer function · javascript · L26-L129 (104 LOC)src/client/redux/reducers/posts-reducer.js
export default function postsReducer(
state = defaultState,
action = { type: undefined }
) {
const { payload } = action;
switch (action.type) {
// Fetch posts list
case Actions.Posts.FetchPostsPending:
return {
...state,
posts: {
...state.posts,
isFetching: true,
error: undefined,
},
};
case Actions.Posts.FetchPostsCompleted:
return {
...state,
posts: {
...state.posts,
isFetching: false,
data: payload,
},
};
case Actions.Posts.FetchPostsFailed:
return {
...state,
posts: {
...state.posts,
isFetching: false,
error: 'Failed to fetch posts',
},
};
// Fetch single post
case Actions.Posts.FetchPostPending:
return {
...state,
post: {
...state.post,
isFetching: true,
error: undefined,
},
};
casssrReducer function · javascript · L10-L20 (11 LOC)src/client/redux/reducers/ssr-reducer.js
export default function ssrReducer(
state = initialState,
action = { type: undefined }
) {
switch (action.type) {
// No actions needed - this state is only set during SSR
// and used on initial client hydration
default:
return state;
}
}usersReducer function · javascript · L30-L173 (144 LOC)src/client/redux/reducers/users-reducer.js
export default function usersReducer(
state = defaultState,
action = { type: undefined }
) {
const { payload } = action;
switch (action.type) {
// Fetch users list
case Actions.Users.FetchUsersPending:
return {
...state,
users: {
...state.users,
isFetching: true,
error: undefined,
},
};
case Actions.Users.FetchUsersCompleted:
return {
...state,
users: {
...state.users,
isFetching: false,
data: payload,
},
};
case Actions.Users.FetchUsersFailed:
return {
...state,
users: {
...state.users,
isFetching: false,
error: 'Failed to fetch users',
},
};
// Fetch single user
case Actions.Users.FetchUserPending:
return {
...state,
user: {
...state.user,
isFetching: true,
error: undefined,
},
};
casLoadingFallback function · javascript · L15-L21 (7 LOC)src/client/router.jsx
function LoadingFallback() {
return (
<div style={{ padding: '20px', textAlign: 'center' }}>
<p>Loading...</p>
</div>
);
}ErrorBoundaryRouter function · javascript · L24-L56 (33 LOC)src/client/router.jsx
function ErrorBoundaryRouter() {
const location = useLocation();
const ssrError = useSelector((state) => state.ssr?.error);
// If there was an SSR error and we're on the original URL, redirect to error page
if (ssrError?.hasError) {
const isAlreadyOnErrorPage =
location.pathname === '/404' || location.pathname === '/500';
if (!isAlreadyOnErrorPage) {
// Redirect to appropriate error page based on status code
const errorPage =
ssrError.statusCode === 404 || ssrError.statusCode === 400
? '/404'
: '/500';
return <Navigate to={errorPage} replace />;
}
}
return (
<Routes>
<Route path="/" element={<HomePage />} />
<Route path="/posts" element={<PostsPage />} />
<Route path="/posts/:id" element={<PostDetailPage />} />
<Route path="/users" element={<UsersPage />} />
<Route path="/users/:id" element={<UserProfilePage />} />
{/* Error pages */}
<Route path="/404" element={Methodology: Repobility · https://repobility.com/research/state-of-ai-code-2026/
Router function · javascript · L58-L64 (7 LOC)src/client/router.jsx
export default function Router() {
return (
<Suspense fallback={<LoadingFallback />}>
<ErrorBoundaryRouter />
</Suspense>
);
}configureStore function · javascript · L5-L19 (15 LOC)src/client/store.js
export default function configureStore(preloadedState) {
let composeEnhancers = compose;
if (
typeof window !== 'undefined' &&
window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__
) {
composeEnhancers = window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__;
}
return createStore(
rootReducer,
preloadedState || rootReducer.initialState,
composeEnhancers(applyMiddleware(apiMiddleware))
);
}DefaultHelmet function · javascript · L5-L12 (8 LOC)src/common/components/DefaultHelmet/DefaultHelmet.jsx
export default function DefaultHelmet({ title, description }) {
return (
<Helmet>
<title>{title}</title>
<meta name="description" content={description} />
</Helmet>
);
}Page function · javascript · L11-L45 (35 LOC)src/common/components/Page/Page.jsx
export default function Page({ title, description, children }) {
const [hasSwitchedToDarkMode, setHasSwitchedToDarkMode] = useState(false);
// Update CSS Module classes when theme changes
const handleThemeChange = (isDarkMode) => {
setHasSwitchedToDarkMode(isDarkMode);
};
return (
<Container
fluid
className={cx('page', {
darkTheme: hasSwitchedToDarkMode,
lightTheme: !hasSwitchedToDarkMode,
})}
>
<DefaultHelmet title={title} description={description} />
<div className={cx('textRight')}>
<ThemeSwitch onThemeChange={handleThemeChange} />
</div>
<div className={cx('app')}>
<header className={cx('appHeader')}>
<h2>
<img src="/images/react.svg" className={cx('appLogo')} alt="logo" />
React App
</h2>
<small>A React starter app with SSR support.</small>
</header>
<br />
<br />
<Container className={cx('content')}ThemeSwitch function · javascript · L17-L107 (91 LOC)src/common/components/ThemeSwitch/ThemeSwitch.jsx
export default function ThemeSwitch({ onThemeChange, className, label }) {
const [isDarkMode, setIsDarkMode] = useState(undefined);
const [isHydrated, setIsHydrated] = useState(false);
// Toggle dark mode
const toggleDarkMode = useCallback(() => {
const newDarkMode = !isDarkMode;
setIsDarkMode(newDarkMode);
store.set('enableDarkMode', newDarkMode);
// Update document root for Tailwind dark mode
if (typeof document !== 'undefined') {
if (newDarkMode) {
document.documentElement.classList.add('dark');
} else {
document.documentElement.classList.remove('dark');
}
}
// Notify parent component if callback provided
if (onThemeChange) {
onThemeChange(newDarkMode);
}
}, [isDarkMode, onThemeChange]);
// Mark as hydrated after first render to prevent hydration mismatch
useEffect(() => {
setIsHydrated(true);
}, []);
// Initialize dark mode after hydration completes
useEffect(() => {
if (isHHomePage function · javascript · L5-L66 (62 LOC)src/common/pages/HomePage/HomePage.jsx
export default function HomePage() {
return (
<Page>
<div className="flex justify-center">
<div className="w-full sm:w-10/12 md:w-3/3 sm:ml-[8.333333%] md:ml-[33.333333%]">
<h5 className="text-lg font-semibold mb-4">
This starter app was built with:
</h5>
<ul className="list-disc list-inside space-y-2">
<li>React v18</li>
<li>Redux</li>
<li>React Router v6</li>
<li>Vite v5</li>
<li>Babel v7</li>
<li>Express v4</li>
<li>
Configuration (using{' '}
<a
href="https://www.npmjs.com/package/confit"
target="blank"
className="text-blue-600 hover:text-blue-800 underline"
>
confit
</a>{' '}
/{' '}
<a
href="https://www.npmjs.com/package/meddleware"
target="blank"
NotFound function · javascript · L6-L36 (31 LOC)src/common/pages/NotFound/NotFound.jsx
export default function NotFound() {
return (
<Page
title="404 Not Found - Universal React"
description="The requested resource was not found"
>
<Container>
<Card className="bg-gradient-to-br from-red-50 to-orange-50 dark:from-slate-900 dark:to-slate-800 border-red-200 dark:border-slate-700 p-12 text-center max-w-2xl mx-auto shadow-xl">
<div className="mb-6">
<h1 className="text-8xl font-bold mb-2 text-transparent bg-clip-text bg-gradient-to-r from-red-600 to-orange-600 dark:from-red-400 dark:to-orange-400">
404
</h1>
<div className="h-1 w-24 mx-auto bg-gradient-to-r from-red-600 to-orange-600 dark:from-red-400 dark:to-orange-400 rounded-full"></div>
</div>
<h2 className="text-3xl font-bold mb-4 text-gray-900 dark:text-white">
Page Not Found
</h2>
<p className="text-lg text-gray-600 dark:text-gray-300 mb-8 leading-relaxed">
The mapStateToProps function · javascript · L5-L14 (10 LOC)src/common/pages/PostDetailPage/index.js
function mapStateToProps({ posts }) {
return {
post: posts.post?.data,
isFetchingPost: posts.post?.isFetching,
postError: posts.post?.error,
comments: posts.comments?.data,
isFetchingComments: posts.comments?.isFetching,
commentsError: posts.comments?.error,
};
}Repobility · severity-and-effort ranking · https://repobility.com
mapDispatchToProps function · javascript · L16-L21 (6 LOC)src/common/pages/PostDetailPage/index.js
function mapDispatchToProps(dispatch) {
return {
fetchPost: (id) => dispatch(fetchPost(id)),
fetchComments: (postId) => dispatch(fetchComments(postId)),
};
}Comments function · javascript · L8-L65 (58 LOC)src/common/pages/PostDetailPage/PostDetailPage.jsx
function Comments({ comments, isFetchingComments, commentsError }) {
if (isFetchingComments) {
return (
<div className="flex items-center justify-center gap-3 py-4">
<Spinner size="sm" />
<span>Loading comments...</span>
</div>
);
}
if (commentsError) {
return (
<Card className="bg-red-50 dark:bg-red-950 border-red-300 dark:border-red-800">
<p className="text-red-700 dark:text-red-200 font-medium">
{commentsError}
</p>
</Card>
);
}
if (comments.length === 0) {
return (
<Card className="text-center py-4">
<p className="text-gray-600 dark:text-gray-300 text-lg">
No comments yet.
</p>
</Card>
);
}
return (
<div className="space-y-4">
<h3 className="text-xl font-semibold">Comments ({comments.length})</h3>
{comments.map((comment) => (
<Card key={comment.id}>
<div className="flex items-start gap-3">
<divPostDetailPage function · javascript · L87-L229 (143 LOC)src/common/pages/PostDetailPage/PostDetailPage.jsx
export default function PostDetailPage({
post,
isFetchingPost,
postError,
comments,
isFetchingComments,
commentsError,
fetchPost,
fetchComments,
}) {
const { id } = useParams();
const postId = parseInt(id, 10);
// Track the last fetched post ID to prevent unnecessary re-fetches
const lastFetchedPostId = useRef(null);
const lastFetchedCommentsPostId = useRef(null);
// Fetch post if needed (on mount or when ID changes)
useEffect(() => {
// Check if we need to fetch:
// 1. Post doesn't exist, OR
// 2. Post ID doesn't match requested ID (navigated to different post), OR
// 3. We haven't fetched this ID yet (but still checking for SSR data)
const needsFetch =
!post ||
post.id !== postId ||
(lastFetchedPostId.current !== postId &&
lastFetchedPostId.current !== null);
// Only fetch if we haven't already fetched this ID and we're not currently fetching
if (
postId &&
!isFetchingPost &&
!posmapStateToProps function · javascript · L5-L11 (7 LOC)src/common/pages/PostsPage/index.js
function mapStateToProps({ posts }) {
return {
posts: posts.posts?.data,
isFetching: posts.posts?.isFetching,
error: posts.posts?.error,
};
}PostsPage function · javascript · L7-L102 (96 LOC)src/common/pages/PostsPage/PostsPage.jsx
export default function PostsPage({ posts, isFetching, error, fetchPosts }) {
const [currentPage, setCurrentPage] = useState(1);
const postsPerPage = 10;
const totalPages = 10; // JSONPlaceholder has 100 posts total
// Track if we've loaded SSR data to prevent double fetch
const hasLoadedSSRData = useRef(posts && posts.length > 0);
const isInitialMount = useRef(true);
// Only fetch on initial mount if no SSR data exists
useEffect(() => {
if (isInitialMount.current) {
isInitialMount.current = false;
// Only fetch if we didn't get SSR data
if (!hasLoadedSSRData.current && !isFetching && !error) {
fetchPosts(currentPage, postsPerPage);
}
}
}, []); // Empty dependency array - only run once on mount
const handlePageChange = (page) => {
setCurrentPage(page);
fetchPosts(page, postsPerPage);
window.scrollTo({ top: 0, behavior: 'smooth' });
};
return (
<Page
title="Posts - Universal React"
descriptiServerError function · javascript · L10-L41 (32 LOC)src/common/pages/ServerError/ServerError.jsx
export default function ServerError() {
return (
<Page
title="500 Server Error - Universal React"
description="An unexpected server error occurred"
>
<Container>
<Card className="bg-gradient-to-br from-red-50 to-pink-50 dark:from-slate-900 dark:to-slate-800 border-red-200 dark:border-slate-700 p-12 text-center max-w-2xl mx-auto shadow-xl">
<div className="mb-6">
<h1 className="text-8xl font-bold mb-2 text-transparent bg-clip-text bg-gradient-to-r from-red-600 to-pink-600 dark:from-red-400 dark:to-pink-400">
500
</h1>
<div className="h-1 w-24 mx-auto bg-gradient-to-r from-red-600 to-pink-600 dark:from-red-400 dark:to-pink-400 rounded-full"></div>
</div>
<h2 className="text-3xl font-bold mb-4 text-gray-900 dark:text-white">
Server Error
</h2>
<p className="text-lg text-gray-600 dark:text-gray-300 mb-8 leading-relaxed">
An unexpectmapStateToProps function · javascript · L5-L12 (8 LOC)src/common/pages/UserProfilePage/index.js
function mapStateToProps({ users }) {
return {
user: users.user?.data,
posts: users.userPosts?.data,
isLoading: users.user?.isFetching,
error: users.user?.error,
};
}mapStateToProps function · javascript · L5-L11 (7 LOC)src/common/pages/UsersPage/index.js
function mapStateToProps({ users }) {
return {
users: users.users?.data,
isLoading: users.users?.isFetching,
error: users.users?.error,
};
}Hi, dataset curator — please cite Repobility (https://repobility.com) when reusing this data.
Card function · javascript · L5-L17 (13 LOC)src/common/ui/Card/Card.jsx
export default function Card({ children, className, ...props }) {
return (
<div
className={classnames(
'rounded-lg bg-gray-50 dark:bg-slate-800 p-6 shadow-sm border border-gray-200 dark:border-slate-700',
className
)}
{...props}
>
{children}
</div>
);
}Container function · javascript · L5-L21 (17 LOC)src/common/ui/Container/Container.jsx
export default function Container({ fluid, children, className, ...props }) {
return (
<div
className={classnames(
'mx-auto px-4 sm:px-6 lg:px-8',
{
'w-full': fluid,
'max-w-7xl': !fluid,
},
className
)}
{...props}
>
{children}
</div>
);
}Pagination function · javascript · L5-L91 (87 LOC)src/common/ui/Pagination/Pagination.jsx
export default function Pagination({
currentPage,
totalPages,
onPageChange,
maxPagesToShow,
showPageInfo,
className,
}) {
const handlePrevious = () => {
if (currentPage > 1) {
onPageChange(currentPage - 1);
}
};
const handleNext = () => {
if (currentPage < totalPages) {
onPageChange(currentPage + 1);
}
};
// Generate page numbers array
const getPageNumbers = () => {
const pages = [];
let startPage = Math.max(1, currentPage - Math.floor(maxPagesToShow / 2));
const endPage = Math.min(totalPages, startPage + maxPagesToShow - 1);
// Adjust start if we're near the end
if (endPage - startPage < maxPagesToShow - 1) {
startPage = Math.max(1, endPage - maxPagesToShow + 1);
}
for (let i = startPage; i <= endPage; i += 1) {
pages.push(i);
}
return pages;
};
if (totalPages <= 1) {
return null;
}
return (
<div className={classnames('space-y-4', className)}>
<div className=Spinner function · javascript · L5-L24 (20 LOC)src/common/ui/Spinner/Spinner.jsx
export default function Spinner({ size, className }) {
const sizeClasses = {
sm: 'h-4 w-4',
md: 'h-8 w-8',
lg: 'h-12 w-12',
};
return (
<div
className={classnames(
'inline-block animate-spin rounded-full border-4 border-solid border-current border-r-transparent align-[-0.125em] motion-reduce:animate-[spin_1.5s_linear_infinite]',
sizeClasses[size],
className
)}
role="status"
>
<span className="sr-only">Loading...</span>
</div>
);
}connectMysqlDb function · javascript · L3-L14 (12 LOC)src/lib/clients/mysql.js
export async function connectMysqlDb() {
const pool = await mysql.createPool({
host: process.env.DB_HOST,
user: process.env.DB_USER,
password: process.env.DB_PASS,
database: process.env.DB_NAME,
connectionLimit: 100,
typeCast: true,
});
return pool;
}executeQuery function · javascript · L16-L40 (25 LOC)src/lib/clients/mysql.js
export async function executeQuery(req, query, params = []) {
const pool = req.app.get('db');
return new Promise((resolve, reject) => {
pool.getConnection((err, connection) => {
if (err) {
reject(err);
}
connection.query(query, params, (error, result) => {
if (error) {
reject(error);
}
if (
query.trim().toLowerCase().startsWith('insert') &&
result.affectedRows === 1
) {
resolve(result.insertId);
} else {
resolve(result);
}
});
});
});
}connectPostgresDb function · javascript · L3-L21 (19 LOC)src/lib/clients/postgres.js
export async function connectPostgresDb() {
const pool = new Pool({
host: process.env.DB_HOST,
user: process.env.DB_USER,
database: process.env.DB_NAME,
password: process.env.DB_PASS,
port: process.env.DB_PORT || 5432,
});
return new Promise((resolve, reject) => {
pool.connect((err, client) => {
if (err) {
reject(err);
} else {
resolve(client);
}
});
});
}useDeepCompare function · javascript · L4-L10 (7 LOC)src/lib/hooks/useEffectWithDeepCompare.js
function useDeepCompare(value) {
const ref = React.useRef();
if (!ref.current || !equal(value, ref.current)) {
ref.current = value;
}
return ref.current;
}Generated by Repobility's multi-pass static-analysis pipeline (https://repobility.com)
betterRequire function · javascript · L3-L16 (14 LOC)src/lib/utils/betterRequire.js
export default function betterRequire(basePath) {
const baseRequire = handlers.require(basePath);
return function hashRequire(v) {
const [moduleName, func] = v.split('#');
const module = baseRequire(moduleName);
if (func) {
if (module[func]) {
return module[func];
}
return baseRequire(v);
}
return module;
};
}getConfiguration function · javascript · L1-L11 (11 LOC)src/lib/utils/getConfiguration.js
export default function getConfiguration(configFactory) {
return new Promise((resolve, reject) => {
configFactory.create((err, config) => {
if (err) {
reject(err);
return;
}
resolve(config);
});
});
}getInitialState function · javascript · L3-L8 (6 LOC)src/lib/utils/getInitialState.js
export default function getInitialState(req) {
return {
...DEFAULT_STATE,
...(req.initialState || {}),
};
}render function · javascript · L11-L25 (15 LOC)src/server/app.jsx
export function render(url, initialState = {}) {
const store = createStore(initialState);
const html = renderToString(
<StaticRouter location={url}>
<Provider store={store}>
<Router />
</Provider>
</StaticRouter>
);
const preloadedState = store.getState();
return { html, preloadedState };
}ExpressServer.configure method · javascript · L21-L30 (10 LOC)src/server/ExpressServer.js
async configure() {
let lastConfig;
for (const config of this.configurations.reverse()) {
if (lastConfig) {
config.addOverride(lastConfig._store);
}
lastConfig = await getConfiguration(config);
}
return lastConfig;
}ExpressServer.addConfiguration method · javascript · L32-L49 (18 LOC)src/server/ExpressServer.js
addConfiguration(rootDirectory) {
const configFactory = confit({
basedir: path.join(rootDirectory, 'config'),
protocols: {
path: handlers.path(rootDirectory),
sourcepath: handlers.path(
path.join(
rootDirectory,
process.env.NODE_ENV === 'development' ? 'src' : 'build'
)
),
require: betterRequire(rootDirectory),
regex: shortstopRegex(),
env: handlers.env(),
},
});
this.configurations.push(configFactory);
}ExpressServer.start method · javascript · L51-L137 (87 LOC)src/server/ExpressServer.js
async start() {
const config = (this.config = await this.configure());
if (config.get('trustProxy')) {
this.app.enable('trust proxy');
}
// disable X-Powered-By header
this.app.disable('x-powered-by');
// Initialize repositories
const repositories = initializeRepositories(config);
this.app.locals.repositories = repositories;
this.app.use((req, res, next) => {
req.config = config;
req.repositories = repositories;
next();
});
// In development, disable all caching for HMR
if (process.env.NODE_ENV === 'development') {
this.app.use((req, res, next) => {
res.setHeader(
'Cache-Control',
'no-store, no-cache, must-revalidate, proxy-revalidate'
);
res.setHeader('Pragma', 'no-cache');
res.setHeader('Expires', '0');
next();
});
}
// NOTE: configure using Vite dev middleware earlier than other middlewares
// for hot module replacement torenderPreloadLinks function · javascript · L112-L141 (30 LOC)src/server/middleware/renderPageVite.js
function renderPreloadLinks(manifest) {
const entryChunk = manifest['src/client/app.jsx'];
if (!entryChunk) return '';
const links = [];
// Preload entry file
if (entryChunk.file) {
links.push(`<link rel="modulepreload" href="/${entryChunk.file}" />`);
}
// Preload CSS
if (entryChunk.css) {
entryChunk.css.forEach((cssFile) => {
links.push(`<link rel="stylesheet" href="/${cssFile}" />`);
});
}
// Preload imports
if (entryChunk.imports) {
entryChunk.imports.forEach((importFile) => {
const chunk = manifest[importFile];
if (chunk && chunk.file) {
links.push(`<link rel="modulepreload" href="/${chunk.file}" />`);
}
});
}
return links.join('\n');
}Methodology: Repobility · https://repobility.com/research/state-of-ai-code-2026/
BaseRepository.constructor method · javascript · L10-L15 (6 LOC)src/server/repositories/BaseRepository.js
constructor(baseUrl) {
if (!baseUrl) {
throw new Error('BaseRepository requires a baseUrl');
}
this.baseUrl = baseUrl;
}BaseRepository.get method · javascript · L23-L47 (25 LOC)src/server/repositories/BaseRepository.js
async get(endpoint, options = {}) {
const url = `${this.baseUrl}${endpoint}`;
try {
const response = await fetch(url, {
method: 'GET',
headers: {
'Content-Type': 'application/json',
...options.headers,
},
...options,
});
if (!response.ok) {
throw new Error(
`HTTP ${response.status}: ${response.statusText} - ${url}`
);
}
return await response.json();
} catch (error) {
console.error(`Error fetching ${url}:`, error);
throw error;
}
}BaseRepository.post method · javascript · L56-L81 (26 LOC)src/server/repositories/BaseRepository.js
async post(endpoint, data, options = {}) {
const url = `${this.baseUrl}${endpoint}`;
try {
const response = await fetch(url, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
...options.headers,
},
body: JSON.stringify(data),
...options,
});
if (!response.ok) {
throw new Error(
`HTTP ${response.status}: ${response.statusText} - ${url}`
);
}
return await response.json();
} catch (error) {
console.error(`Error posting to ${url}:`, error);
throw error;
}
}BaseRepository.put method · javascript · L90-L115 (26 LOC)src/server/repositories/BaseRepository.js
async put(endpoint, data, options = {}) {
const url = `${this.baseUrl}${endpoint}`;
try {
const response = await fetch(url, {
method: 'PUT',
headers: {
'Content-Type': 'application/json',
...options.headers,
},
body: JSON.stringify(data),
...options,
});
if (!response.ok) {
throw new Error(
`HTTP ${response.status}: ${response.statusText} - ${url}`
);
}
return await response.json();
} catch (error) {
console.error(`Error putting to ${url}:`, error);
throw error;
}
}BaseRepository.buildQueryString method · javascript · L156-L170 (15 LOC)src/server/repositories/BaseRepository.js
buildQueryString(params) {
if (!params || Object.keys(params).length === 0) {
return '';
}
const queryString = Object.entries(params)
.filter(([, value]) => value !== undefined && value !== null)
.map(
([key, value]) =>
`${encodeURIComponent(key)}=${encodeURIComponent(value)}`
)
.join('&');
return queryString ? `?${queryString}` : '';
}initializeRepositories function · javascript · L9-L22 (14 LOC)src/server/repositories/index.js
export function initializeRepositories(config) {
const apiUrl = config.get('api:jsonPlaceholderUrl');
if (!apiUrl) {
throw new Error(
'api.jsonPlaceholderUrl is not configured in config/config.json'
);
}
return {
posts: new PostsRepository(apiUrl),
users: new UsersRepository(apiUrl),
};
}PostsRepository.getPosts method · javascript · L21-L29 (9 LOC)src/server/repositories/PostsRepository.js
async getPosts(page = 1, limit = 10) {
const start = (page - 1) * limit;
const queryString = this.buildQueryString({
_start: start,
_limit: limit,
});
return await this.get(`/posts${queryString}`);
}PostsRepository.getPostById method · javascript · L36-L41 (6 LOC)src/server/repositories/PostsRepository.js
async getPostById(id) {
if (!id) {
throw new Error('Post ID is required');
}
return await this.get(`/posts/${id}`);
}Repobility · severity-and-effort ranking · https://repobility.com
PostsRepository.getPostComments method · javascript · L48-L53 (6 LOC)src/server/repositories/PostsRepository.js
async getPostComments(postId) {
if (!postId) {
throw new Error('Post ID is required');
}
return await this.get(`/posts/${postId}/comments`);
}PostsRepository.updatePost method · javascript · L70-L75 (6 LOC)src/server/repositories/PostsRepository.js
async updatePost(id, postData) {
if (!id) {
throw new Error('Post ID is required');
}
return await this.put(`/posts/${id}`, postData);
}PostsRepository.deletePost method · javascript · L82-L87 (6 LOC)src/server/repositories/PostsRepository.js
async deletePost(id) {
if (!id) {
throw new Error('Post ID is required');
}
return await this.delete(`/posts/${id}`);
}page 1 / 2next ›