Skip to main content
The Products Service manages the product catalog, handling CRUD operations with automatic sort order management and intelligent JSON parsing for complex fields.

Overview

This service provides a complete interface for managing products, including automatic sortOrder assignment, JSON field parsing, and repository interaction.

Dependencies

  • productsRepository - Database operations for products

Methods

getAllProducts()

Retrieves all products from the database.
import { productsService } from '$lib/server/services/products.service.js';

const products = await productsService.getAllProducts();
products
array
Array of product objects, each containing:
  • id: Product identifier
  • name: Product name
  • description: Product description
  • align: Text alignment (left/right)
  • accentColor: Highlight color
  • displayType: Display variant
  • images: Array of image URLs
  • features: Array of feature objects
  • categories: Array of category strings
  • sortOrder: Display order

Implementation Details

Source: src/lib/server/services/products.service.js:5-7

addProduct()

Creates a new product with automatic sort order assignment.
import { productsService } from '$lib/server/services/products.service.js';

await productsService.addProduct({
  name: 'Producto Nuevo',
  description: 'Descripción del producto',
  align: 'left',
  accentColor: '#e4002b',
  displayType: 'standard',
  images: JSON.stringify([
    'https://example.com/image1.jpg',
    'https://example.com/image2.jpg'
  ]),
  features: JSON.stringify([
    { icon: 'check', text: 'Alta calidad' },
    { icon: 'star', text: 'Mejor precio' }
  ]),
  categories: JSON.stringify(['Construcción', 'Hogar'])
});
name
string
required
Product name
description
string
required
Product description
align
string
Text alignment: left or right
accentColor
string
Accent color in hex format (e.g., #e4002b)
displayType
string
Display variant: standard, featured, etc.
images
string | array
Product images. Can be:
  • JSON string: '["url1", "url2"]'
  • Array: ['url1', 'url2']
features
string | array
Product features. Can be:
  • JSON string: '[{"icon": "check", "text": "Feature"}]'
  • Array: [{icon: 'check', text: 'Feature'}]
categories
string | array
Product categories. Can be:
  • JSON string: '["Cat1", "Cat2"]'
  • Array: ['Cat1', 'Cat2']

Automatic Sort Order

The service automatically calculates sortOrder:
const existing = await productsRepository.getAll();
const nextOrder = existing.length > 0 
  ? existing[existing.length - 1].sortOrder + 1 
  : 0;
New products are appended to the end of the list.

JSON Parsing

The service intelligently handles JSON fields:
images: typeof images === 'string' ? JSON.parse(images) : images
This allows form data (strings) and programmatic data (arrays) to work seamlessly.

Implementation Details

Source: src/lib/server/services/products.service.js:10-21

updateProduct()

Updates an existing product.
import { productsService } from '$lib/server/services/products.service.js';

await productsService.updateProduct(1, {
  name: 'Updated Product Name',
  description: 'New description',
  images: ['https://example.com/new-image.jpg'],
  features: [
    { icon: 'check', text: 'Updated feature' }
  ],
  categories: ['New Category']
});
id
number
required
Product ID to update
name
string
Updated product name
description
string
Updated description
align
string
Updated alignment
accentColor
string
Updated accent color
displayType
string
Updated display type
images
string | array
Updated images (JSON string or array)
features
string | array
Updated features (JSON string or array)
categories
string | array
Updated categories (JSON string or array)

Implementation Details

Source: src/lib/server/services/products.service.js:24-31
Only provided fields are updated. Omitted fields remain unchanged.

deleteProduct()

Deletes a product by ID.
import { productsService } from '$lib/server/services/products.service.js';

await productsService.deleteProduct(1);
id
number
required
Product ID to delete

Implementation Details

Source: src/lib/server/services/products.service.js:34-36

Usage Examples

Complete Product Management in SvelteKit

// src/routes/admin/products/+page.server.js
import { productsService } from '$lib/server/services/products.service.js';
import { fail } from '@sveltejs/kit';

export async function load() {
  const products = await productsService.getAllProducts();
  return { products };
}

export const actions = {
  add: async ({ request }) => {
    const formData = await request.formData();
    
    try {
      await productsService.addProduct({
        name: formData.get('name'),
        description: formData.get('description'),
        align: formData.get('align'),
        accentColor: formData.get('accentColor'),
        displayType: formData.get('displayType'),
        images: formData.get('images'), // JSON string from form
        features: formData.get('features'), // JSON string from form
        categories: formData.get('categories') // JSON string from form
      });
      
      return { success: true };
    } catch (error) {
      return fail(500, { error: error.message });
    }
  },
  
  update: async ({ request }) => {
    const formData = await request.formData();
    const id = parseInt(formData.get('id'));
    
    try {
      await productsService.updateProduct(id, {
        name: formData.get('name'),
        description: formData.get('description'),
        images: formData.get('images'),
        features: formData.get('features'),
        categories: formData.get('categories')
      });
      
      return { success: true };
    } catch (error) {
      return fail(500, { error: error.message });
    }
  },
  
  delete: async ({ request }) => {
    const formData = await request.formData();
    const id = parseInt(formData.get('id'));
    
    try {
      await productsService.deleteProduct(id);
      return { success: true };
    } catch (error) {
      return fail(500, { error: error.message });
    }
  }
};

Programmatic Product Creation

import { productsService } from '$lib/server/services/products.service.js';

// Using arrays directly (no JSON stringification needed)
await productsService.addProduct({
  name: 'Cemento Portland',
  description: 'Cemento de alta resistencia',
  align: 'left',
  accentColor: '#e4002b',
  displayType: 'featured',
  images: [
    'https://cdn.example.com/cemento-1.jpg',
    'https://cdn.example.com/cemento-2.jpg'
  ],
  features: [
    { icon: 'shield', text: 'Alta resistencia' },
    { icon: 'clock', text: 'Secado rápido' },
    { icon: 'check', text: 'Certificado ISO' }
  ],
  categories: ['Construcción', 'Cementos']
});

Data Structure

Product Object

interface Product {
  id: number;
  name: string;
  description: string;
  align: 'left' | 'right';
  accentColor: string;
  displayType: string;
  images: string[];
  features: Array<{
    icon: string;
    text: string;
  }>;
  categories: string[];
  sortOrder: number;
}

Feature Object

interface Feature {
  icon: string;  // Icon identifier (e.g., 'check', 'star', 'shield')
  text: string;  // Feature description
}

JSON Field Handling

The service accepts both formats for complex fields:

From Form Data (String)

{
  images: '["url1.jpg", "url2.jpg"]',
  features: '[{"icon":"check","text":"Feature 1"}]',
  categories: '["Cat1","Cat2"]'
}

From Code (Array/Object)

{
  images: ['url1.jpg', 'url2.jpg'],
  features: [{ icon: 'check', text: 'Feature 1' }],
  categories: ['Cat1', 'Cat2']
}
Both are handled automatically!

Best Practices

When building forms, use hidden inputs or JavaScript to construct JSON strings for complex fields.
Validate JSON strings before submission to prevent parsing errors.
Product order is managed automatically. To reorder products, you’ll need to update sortOrder values directly through the repository.
The service does not handle image uploads. Images should be uploaded separately (e.g., via upload service) and URLs passed to this service.