No slash command · from power-platform-full-stack
Provides an IoC pattern for building UIs against in-memory test data first, then swapping to real backends. Covers service interfaces, domain models with DTOs, in-memory implementations, and React Query integration with cache invalidation.
Ships in power-platform-full-stack. Installing the plugin adds it to Claude Code.
What the skill costs in Claude's context, stage by stage
Name and description: Claude knows it exists.
SKILL.md joins the conversation and stays.
Read when SKILL.md points to them.
Build your entire UI against in-memory test data first. Connect to real data sources later.
This pattern applies to any Power Platform frontend — Code Apps (Dataverse, Azure SQL), Power Pages code sites (Dataverse Web API), or any app that consumes external data.
Create a TypeScript interface for each data entity your app needs. The interface describes what the app needs, not how any specific backend works.
// src/services/interfaces.ts
export interface IEntityService<T> {
getAll(options?: QueryOptions): Promise<T[]>;
getById(id: string): Promise<T | null>;
create(entity: Omit<T, "id">): Promise<T>;
update(id: string, changes: Partial<T>): Promise<void>;
delete(id: string): Promise<void>;
}
export interface QueryOptions {
filter?: string;
orderBy?: string;
top?: number;
select?: string[];
}
Each domain entity gets three type definitions:
// src/features/projects/models/Project.ts
/** Domain model — what the app works with */
export interface Project {
id: string;
name: string;
description: string | null;
status: "Active" | "Completed" | "On Hold";
startDate: Date;
budget: number;
createdOn: Date;
modifiedOn: Date;
}
/** Fields for creating a new record — only user-controlled fields */
export interface CreateProjectDto {
name: string;
description?: string;
status?: Project["status"];
startDate?: Date;
budget?: number;
}
/** Fields for updating — all optional, only include what changed */
export interface UpdateProjectDto {
name?: string;
description?: string;
status?: Project["status"];
startDate?: Date;
budget?: number;
}
/** Query filters */
export interface ProjectFilters {
status?: Project["status"];
search?: string;
}
// src/services/interfaces.ts (continued)
export interface IProjectService extends IEntityService<Project> {
getByStatus(status: Project["status"]): Promise<Project[]>;
}
export interface ITaskService extends IEntityService<Task> {
getByProject(projectId: string): Promise<Task[]>;
}
Include pagination in your service interface from the start — don't bolt it on later:
interface PageOptions {
page: number;
pageSize: number;
sortField?: string;
sortDirection?: 'asc' | 'desc';
search?: string;
filter?: Record<string, string>;
}
interface PagedResult<T> {
items: T[];
totalCount: number;
page: number;
pageSize: number;
}
interface IEntityService<T> {
getPage(options: PageOptions): Promise<PagedResult<T>>;
getStatusCounts(): Promise<Record<string, number>>;
getById(id: string): Promise<T | null>;
create(dto: CreateDto): Promise<T>;
update(id: string, dto: UpdateDto): Promise<T>;
delete(id: string): Promise<void>;
}
Known Platform Limitations:
$skip is supported via the generated service's IGetAllOptions.
Use skip + top for standard server-side paging, or skipToken for continuation-based paging.$skip is NOT supported on the /_api/ endpoint. Use FetchXML paging
instead — FetchXML supports page and count attributes for true server-side pagination, plus
a paging-cookie for efficient continuation. Wrap FetchXML queries via /_api/ using
?fetchXml=<encoded-xml>.If the user will see sorted, filtered, or paginated data — the server must do the sorting, filtering, and paginating. The client only renders what the server returns. No exceptions.
These rules are MANDATORY for every service implementation and every list/grid screen. Violations cause wrong data, wrong counts, and systems that break at scale.
// BAD — client-side sort only sorts the current page
const sorted = [...items].sort((a, b) => a.price - b.price);
// GOOD — sort parameter sent to server
list(filters, page, pageSize, sortColumn: "price", sortDirection: "asc")
// Server adds: $orderby=zava_price asc
Why: Sorting 25 items on page 1 does NOT produce the same result as sorting the entire 10,000-row dataset and returning the first 25. Client-side sort is a lie when pagination is active.
In-memory implementation exception: In-memory services hold all data in arrays, so sorting the array then slicing for pagination is correct. But the interface MUST accept sort parameters so that real implementations can delegate to the server.
// BAD — fetch all, filter in browser
const all = await service.list({}, 1, 1000);
const filtered = all.items.filter(x => x.status === "Active");
// GOOD — filter parameter sent to server
const result = await service.list({ status: "Active" }, 1, 25);
// Server adds: $filter=statuscode eq 1
Why: Client-side filtering makes totalCount wrong. If the server says 100 records
total but only 12 match the filter, the pagination shows 4 pages but pages 2-4 are empty.
Users see ghost pages.
corollary: Every filter on the UI MUST have a corresponding server-side query parameter. If the server can't filter by a field, either:
Never silently filter client-side and pretend the pagination is correct.
// BAD — fetch all, slice in browser
const all = await fetch("/api/properties"); // returns 10,000 rows
const page = all.slice((pageNum - 1) * 25, pageNum * 25);
// GOOD — page parameters sent to server
const result = await fetch("/api/properties?$top=25&$skip=50"); // returns 25 rows
Why: Fetching 10,000 records to display 25 wastes bandwidth, memory, and time. Response times degrade linearly with dataset size.
When true server-side paging isn't possible (e.g., Dataverse OData lacks $skip):
$skiptoken continuation-based pagingpage + count attributes// BAD — client-side text search
const results = items.filter(x =>
x.name.toLowerCase().includes(searchText.toLowerCase())
);
// GOOD — search sent to server
const result = await service.list({ search: searchText }, 1, 25);
// Server adds: $filter=contains(zava_name, 'searchText')
Why: Client-side search only searches the current page. A user searching for "Penthouse" won't find it if it's on page 4 and they're viewing page 1.
// BAD — fetch all records to count them
const all = await service.list({}, 1, 99999);
const activeCount = all.items.filter(x => x.status === "Active").length;
// GOOD — use server-side count or aggregate
const counts = await service.getStatusCounts();
// Server uses: GET /api/properties?$count=true&$filter=statuscode eq 1
// Or: FetchXML aggregate queries
Why: Loading 10,000 records to display a dashboard number "Active: 47" is catastrophically wasteful. Dashboard screens with multiple KPIs multiply the problem.
Every list method in the service interface MUST accept:
any)// GOOD — interface makes delegation explicit
interface IPropertyService {
list(
filters?: PropertyFilters,
page?: number,
pageSize?: number,
sortColumn?: string,
sortDirection?: SortDirection
): Promise<PagedResult<Property>>;
}
If a parameter exists in the interface, BOTH the in-memory AND real implementations MUST honor it. The in-memory implementation sorts/filters/pages its arrays. The real implementation delegates to the server.
Before marking any list screen as complete, verify:
totalCount in PagedResult reflects the filtered count, not the total table sizeArray.prototype.sort() or .filter() on fetched PagedResult.items in screen componentsplaceholderData: keepPreviousDataSORT_FIELDS / SORT_MAP keyed by DataGrid columnIdisLoading, isError, and data separately (not combined into one check)onSuccess calls useNotificationStore.getState().enqueue() with a success messageonError calls useNotificationStore.getState().enqueue() with an error messageSORT_FIELDS map (not generic string-key bracket notation)The DataGrid columnId values are the contract between UI columns and service sort logic.
Both in-memory and real implementations MUST define a map from these IDs to their sort mechanism.
// In-memory: map columnId → accessor function
const SORT_FIELDS: Record<string, (item: Entity) => string | number | Date> = {
title: (p) => p.name.toLowerCase(),
price: (p) => p.price,
status: (p) => p.status,
};
// Real (Dataverse): map columnId → OData column name
private static SORT_MAP: Record<string, string> = {
title: "prefix_name",
price: "prefix_price",
status: "statuscode",
};
Why two maps? The in-memory service sorts arrays using accessor functions.
The Dataverse service builds $orderby clauses using column names. Both are keyed
by the same columnId strings from the DataGrid, so the UI never knows which
implementation is active.
Default sort: When sortColumn is not in the map, fall back to a sensible default
(e.g., modifiedOn desc). Never throw or return unsorted data.
Some searches are impossible server-side (e.g., OData cannot contains() on lookup
display names). When client-side filtering is unavoidable:
// Client-side: OData can't filter on lookup display namestotalCount:// Client-side search on returned items (documented limitation)
const filteredItems = useMemo(() => {
if (!search) return data?.items ?? [];
const q = search.toLowerCase();
return (data?.items ?? []).filter(item =>
item.displayName?.toLowerCase().includes(q)
);
}, [data, search]);
// Pagination uses filtered count when client-side search is active
<Pagination
totalItems={search ? filteredItems.length : data?.totalCount ?? 0}
...
/>
When the app is running with in-memory mock data, display a visible indicator:
// In your AppShell or TopBar component:
{serviceRegistry.isUsingMockData && (
<Badge appearance="tint" color="warning">MOCK DATA</Badge>
)}
This prevents confusion during testing and demos. The user should always know whether they're looking at real or simulated data.
Data entering the app from external sources (APIs, AI services, user input) must be validated and normalized at the service boundary before reaching the UI layer.
Clamp numeric values from external APIs — AI-generated scores, ratings, or computed values can exceed expected ranges (e.g., a score of 105 when the UI expects 0–100). Clamp at the service mapper, not in the component:
// In the domain mapper (service layer):
score: Math.max(0, Math.min(100, raw.aiScore ?? 0)),
Wrap JSON.parse of external API responses in try/catch — External APIs may
return malformed JSON, HTML error pages, or empty bodies. Always catch parse errors
and throw a user-friendly error:
let parsed: ExternalResponse;
try {
parsed = JSON.parse(responseText);
} catch {
throw new Error("Invalid response from external service");
}
Date formatting: use toISOString(), never String() — String(dateObject)
produces non-ISO format like "Sat Feb 01 2026 00:00:00 GMT..." which is unparseable
by many backends. Always use date instanceof Date ? date.toISOString() : date for
reliable serialization.
Date-only fields: append T00:00:00 for local-time interpretation — When saving
a date-only value (e.g., a closing date), append T00:00:00 to the ISO string to
prevent UTC interpretation that shifts the date backward in negative-offset timezones.
InMemory services: resolve lookup display names via lazy import — When an
in-memory create() or update() method needs to resolve a lookup ID to a display
name (e.g., to populate a categoryName field), use lazy import() of the service
registry to prevent circular module dependencies:
async create(dto: CreateDto): Promise<Entity> {
// Lazy import to break circular dependency
const { getService } = await import("../serviceRegistry");
const categoryService = getService("categories");
const category = await categoryService.getById(dto.categoryId);
// ... populate entity with category.name
}
Create implementations that store data in arrays. These run entirely in the browser with zero external dependencies.
See resources/in-memory-implementation.md for the full InMemoryProjectService class
implementing all interface methods with array storage.
await new Promise(r => setTimeout(r, 200)) at the
top of methods to test loading states and spinnersCentralize service resolution so the app consumes interfaces, not implementations. One swap point controls which implementations are active.
// src/services/serviceRegistry.ts
import type { IProjectService, ITaskService } from "./interfaces";
import { InMemoryProjectService } from "./in-memory/InMemoryProjectService";
import { InMemoryTaskService } from "./in-memory/InMemoryTaskService";
// --- Swap point: change these imports when connecting real backends ---
// import { DataverseProjectService } from "./dataverse/DataverseProjectService";
// import { AzureSqlProjectService } from "./azure-sql/AzureSqlProjectService";
const services = {
projects: new InMemoryProjectService() as IProjectService,
tasks: new InMemoryTaskService() as ITaskService,
};
export function getService<K extends keyof typeof services>(name: K): (typeof services)[K] {
return services[name];
}
// --- Test isolation: reset singleton state between tests ---
export function _resetForTesting(): void {
services.projects = new InMemoryProjectService();
services.tasks = new InMemoryTaskService();
}
Test isolation is critical. The registry uses module-level singletons — state persists between tests unless explicitly reset. Always call
_resetForTesting()inbeforeEach()during unit tests. Seeresources/testing-strategy.mdfor full testing patterns.
For React apps, a context provider gives components access to services via hooks:
// src/services/ServiceContext.tsx
import { createContext, useContext, type ReactNode } from "react";
import type { IProjectService, ITaskService } from "./interfaces";
import { InMemoryProjectService } from "./in-memory/InMemoryProjectService";
import { InMemoryTaskService } from "./in-memory/InMemoryTaskService";
interface Services {
projects: IProjectService;
tasks: ITaskService;
}
const defaultServices: Services = {
projects: new InMemoryProjectService(),
tasks: new InMemoryTaskService(),
};
const ServiceContext = createContext<Services>(defaultServices);
export function ServiceProvider({ children, services }: { children: ReactNode; services?: Partial<Services> }) {
const merged = { ...defaultServices, ...services };
return <ServiceContext.Provider value={merged}>{children}</ServiceContext.Provider>;
}
export function useServices(): Services {
return useContext(ServiceContext);
}
Usage in components:
const { projects } = useServices();
const allProjects = await projects.getAll({ top: 50 });
All components import from the service registry or context — never from a concrete implementation. This means the entire UI can be built, tested, and demoed with zero backend connectivity.
// src/components/ProjectList.tsx — uses the interface, not the backend
import { useEffect, useState } from "react";
import { useServices } from "../services/ServiceContext";
import type { Project } from "../services/interfaces";
export function ProjectList() {
const { projects } = useServices();
const [items, setItems] = useState<Project[]>([]);
const [loading, setLoading] = useState(true);
useEffect(() => {
projects.getAll({ orderBy: "name asc", top: 50 }).then((data) => {
setItems(data);
setLoading(false);
});
}, [projects]);
if (loading) return <div>Loading...</div>;
return (
<ul>
{items.map((p) => (
<li key={p.id}>{p.name} — {p.status}</li>
))}
</ul>
);
}
For production React apps, use React Query (@tanstack/react-query) instead of raw useEffect.
It provides caching, background refetching, loading/error states, and mutation hooks out of the box.
npm install @tanstack/react-query
Wrap your app with QueryClientProvider:
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
const queryClient = new QueryClient({
defaultOptions: {
queries: {
staleTime: 5 * 60 * 1000, // 5 minutes
retry: 1,
},
},
});
export const App = () => (
<QueryClientProvider client={queryClient}>
{/* app content */}
</QueryClientProvider>
);
See resources/react-query-hooks.md for the complete React Query integration:
query key factory, query hooks, mutation hooks with cache invalidation,
optimistic updates, and component usage patterns.
At this stage you have a fully functional app running on in-memory data. Iterate on the UI, get stakeholder feedback, refine flows — all without touching a backend.
When the UI is approved and stable, create implementations that connect to the real data source. The implementation translates between your domain interface and the backend's raw API.
Every real service method should:
toDomainModel()See resources/real-service-implementation.md for the complete RealProjectService class,
key implementation principles, and graceful degradation patterns.
For platform-specific implementation guidance:
../power-apps-code-apps/resources/dataverse-integration.md../power-apps-code-apps/resources/connector-azure-sql.md../power-pages/resources/webapi-integrate.mdUpdate the service registry to use the real implementations. You can swap all at once or incrementally — one entity at a time:
// src/services/serviceRegistry.ts — after connecting Dataverse
import type { IProjectService, ITaskService } from "./interfaces";
import { RealProjectService } from "./real/RealProjectService";
import { InMemoryTaskService } from "./in-memory/InMemoryTaskService";
const services = {
projects: new RealProjectService() as IProjectService, // ← swapped
tasks: new InMemoryTaskService() as ITaskService, // ← still in-memory
};
export function getService<K extends keyof typeof services>(name: K): (typeof services)[K] {
return services[name];
}
No UI code changes needed. Components still call projects.getAll() — the registry
routes to the real implementation.
After completing each step, run npm run build (or npx tsc --noEmit) to verify there are no type errors. Fix any errors before proceeding to the next step. After Step 4, run the app (npm run dev) and manually verify the in-memory data renders correctly.
Detail screens (record forms) MUST distinguish between loading, error, and not-found states. Combining them into a single check causes infinite spinners when a record doesn't exist.
// BAD — infinite spinner when record doesn't exist
const { data: property, isLoading } = useProperty(id);
if (isLoading || !property) return <Spinner label="Loading..." />;
When id is valid but the record was deleted, isLoading becomes false and data is null.
The !property check keeps showing the spinner forever — the user has no way to know
the record doesn't exist.
const { data: property, isLoading, isError } = useProperty(id);
if (isLoading) return <Spinner label="Loading property..." />;
if (isError || !property) {
return (
<MessageBar intent="error">
<MessageBarBody>
Property not found. It may have been deleted.
<Button appearance="subtle" onClick={() => navigate("/properties")}>
Back to list
</Button>
</MessageBarBody>
</MessageBar>
);
}
Every detail screen MUST have THREE distinct states:
isLoading is true → show SpinnerisError or data is null → show error message with back navigationNever combine loading and not-found into one conditional.
| Resource | Description |
|---|---|
resources/in-memory-implementation.md | Full InMemoryProjectService reference implementation with array storage |
resources/react-query-hooks.md | Query key factory, query/mutation hooks, cache invalidation, optimistic updates, component usage |
resources/real-service-implementation.md | Full RealProjectService class, toDomainModel(), implementation principles, graceful degradation |
resources/testing-strategy.md | Testing patterns for the IoC service layer — unit testing in-memory and real services, testing React Query hooks, service registry test isolation, Vitest configuration |
resources/error-handling.md | Structured error handling pattern — typed errors, error boundary integration, React Query error states, toast notifications |
What SKILL.md sets; muted values are Claude Code's defaults
npx claudepluginhub scottdurow/power-platform-full-stack-skills --plugin power-platform-full-stack16 skills in this plugin
/browser-automationInteractive browser automation and visual validation using Playwright MCP server and GitHub Copilot Agent Mode. Creates a bridge between the agent and a live browser session (including authenticated user context), with optional scripted Playwright test generation for repeatable checks. Triggers on "browser automation", "interactive browser", "playwright mcp", "test the ui", "ui test", "visual test", "visual regression", "check interface", "deployment smoke test", "post-deploy validation", "config validation"./code-reviewDeep code audit and technical review skill. Handles code audits (dead wiring, silent failures, stubs, bloat), architecture decisions, security audits, feature design reviews, refactoring plans, and deployment strategy reviews. Produces actionable reports with file:line references grouped by severity, or structured decision documents with trade-off analysis. Triggers on "code review", "audit the code", "review the code", "find dead code", "find placeholders", "check for stubs", "prune the code", "code cleanup", "implementation review", "completeness check", "find unused code", "architecture decision", "security audit", "design review", "refactoring plan", "deployment review", "team review", "review team", "collaborative review".Other plugins' skills for the same job