more-apartments-astro-integration
v2.1.2
Published
Astro integration for More Apartments REST API
Maintainers
Readme
More Apartments Astro Integration
A fully-typed Astro integration for the More Apartments REST API, providing easy access to property listings, availability, bookings, and content management.
Features
- 🚀 Full TypeScript Support - Complete type definitions for all API responses
- 🎯 Helper Functions - Built-in error handling with simple null-check patterns
- 🔄 Auto Retry Logic - Automatic retry with exponential backoff
- 💾 Response Caching - Configurable caching to reduce API calls
- 🔌 Virtual Modules - Easy importing in Astro components
- ⚡ Astro Optimized - Follows Astro SSR best practices
Installation
npm install more-apartments-astro-integration
# or
bun add more-apartments-astro-integrationQuick Start
1. Configure the Integration
Add to your astro.config.mjs:
import { defineConfig } from 'astro/config';
import moreApartments from 'more-apartments-astro-integration';
export default defineConfig({
integrations: [
moreApartments({
baseUrl: process.env.MORE_APARTMENTS_BASE_URL,
apiKey: process.env.MORE_APARTMENTS_API_KEY,
instance: process.env.MORE_APARTMENTS_INSTANCE,
})
]
});2. Environment Variables
Create .env:
MORE_APARTMENTS_BASE_URL=http://your-api-url
MORE_APARTMENTS_API_KEY=your-api-key
MORE_APARTMENTS_INSTANCE=your-instance-name3. Use Helper Functions (Recommended)
Helper functions provide automatic error handling with simple null checks:
---
// src/pages/property/[slug].astro
import client from 'virtual:more-apartments/client';
import { fetchProperty } from 'more-apartments-astro-integration';
const { slug } = Astro.params;
// Validate parameter
if (!slug) {
return Astro.rewrite("/404");
}
// Fetch property (returns null on error, automatic logging)
const property = await fetchProperty(client, slug);
// Handle missing property
if (!property) {
return Astro.rewrite("/404");
}
// Property is guaranteed non-null here
---
<h1>{property.name}</h1>
<p>{property.description}</p>Why this pattern?
- ✅ No try/catch boilerplate needed
- ✅ Automatic error logging
- ✅ Returns null for simple checks
- ✅ SEO-friendly with
Astro.rewrite()
Available Helper Functions
Single Resource (returns T | null)
import {
fetchProperty,
fetchPage,
fetchPost,
fetchAvailability
} from 'more-apartments-astro-integration';
// Returns Property | null
const property = await fetchProperty(client, 'apartment-slug');
// Returns Page | null
const page = await fetchPage(client, 'about-us');
// Returns Post | null
const post = await fetchPost(client, 'blog-post-slug');
// Returns Availability | null
const availability = await fetchAvailability(
client,
'apartment-slug',
'2024-03-01',
'2024-03-15'
);Collections (returns T[] - empty array on error)
import {
fetchProperties,
searchProperties,
fetchPages,
fetchPosts
} from 'more-apartments-astro-integration';
// Returns { data: Property[], meta: {}, links: {} }
const properties = await fetchProperties(client, { page: 1 });
// Returns Property[] (empty on error)
const results = await searchProperties(client, {
city: 'Amsterdam',
bedrooms: 2,
arrival: '2024-03-01',
departure: '2024-03-07'
});
// Returns Page[] (empty on error)
const pages = await fetchPages(client);
// Returns Post[] (empty on error)
const posts = await fetchPosts(client, { tag: 'news' });Property Search Parameters
interface PropertySearchParams {
// Location filters
city?: string;
area?: string;
street?: string;
// Property filters
property_type?: string;
bedrooms?: number;
bathrooms?: number;
max_persons?: number;
// Amenity filters
elevator?: boolean;
parking?: boolean;
balcony?: boolean;
// Date filters
arrival?: string; // YYYY-MM-DD
departure?: string; // YYYY-MM-DD
guests?: number;
// Legacy filters (deprecated)
destination?: string;
segment?: string;
}Examples
See the examples/ directory for complete working examples:
- Property Detail Page - Single property with error handling
- Property Listing Page - Search with filters
Astro Best Practices
Use Astro.rewrite() for 404s (Not redirect())
✅ RECOMMENDED:
---
if (!property) {
return Astro.rewrite("/404"); // Preserves URL
}
---❌ AVOID:
---
if (!property) {
return Astro.redirect("/404"); // Changes URL
}
---Why Astro.rewrite()?
- Preserves original URL for SEO
- Better user experience (shows what they searched for)
- Doesn't count as a redirect (faster)
API Reference
Properties
// Get single property
const property = await fetchProperty(client, 'apartment-slug');
// Search properties
const properties = await searchProperties(client, {
city: 'Amsterdam',
bedrooms: 2
});
// Get paginated list
const response = await fetchProperties(client, {
page: 1,
per_page: 15
});Availability
// Get availability for date range
const availability = await fetchAvailability(
client,
'apartment-slug',
'2024-03-01',
'2024-03-15'
);Content
// Pages
const pages = await fetchPages(client);
const page = await fetchPage(client, 'about-us');
// Posts
const posts = await fetchPosts(client, {
page: 1,
per_page: 10,
tag: 'news'
});
const post = await fetchPost(client, 'blog-post-slug');Settings
import { fetchSettings } from 'more-apartments-astro-integration';
const mainSettings = await fetchSettings(client, 'main');
const themeSettings = await fetchSettings(client, 'theme');
const propertySettings = await fetchSettings(client, 'properties');
const bookingSettings = await fetchSettings(client, 'booking');TypeScript Types
All types are exported for use in your application:
import type {
Property,
PropertySearchParams,
Page,
Post,
Availability,
MainSettings,
ThemeSettings,
PropertySettings,
BookingSettings,
PaginatedResponse
} from 'more-apartments-astro-integration';Image Utilities
Helper functions for working with property images:
---
import {
getPrimaryImageUrl,
getThumbnailUrl,
getAllImageUrls,
getImageWithAlt,
hasImages,
getImageCount
} from 'more-apartments-astro-integration';
const imageUrl = getPrimaryImageUrl(property, '/placeholder.jpg');
const thumbUrl = getThumbnailUrl(property);
const allImages = getAllImageUrls(property);
const { url, alt } = getImageWithAlt(property, 0);
if (hasImages(property)) {
console.log(`Property has ${getImageCount(property)} images`);
}
---
<img src={imageUrl} alt={alt} />Configuration Options
Full configuration reference:
moreApartments({
// Required
baseUrl: 'http://your-api-url',
instance: 'your-instance',
// Optional
apiKey: process.env.API_KEY,
// Request configuration
timeout: 30000, // Request timeout in ms
retry: {
attempts: 3, // Number of retries
delay: 1000, // Initial delay between retries
},
// Caching
cache: {
enabled: true, // Enable caching
ttl: 300000, // Cache time-to-live (5 minutes)
},
// Integration features
virtualModules: true, // Enable virtual modules
injectClient: true, // Inject global client
addApiRoutes: true, // Add proxy routes (recommended)
apiRoutePrefix: '/api/apartments',
// Development features
instancePath: '../path/to/instance', // Hot-reload instance changes
projectPath: '../path/to/laravel', // Auto-load API key
})Advanced Usage
Direct Client Access (Advanced)
For custom error handling, use the raw client:
---
import client from 'virtual:more-apartments/client';
try {
const property = await client.getProperty('apartment-slug');
// Custom success handling
} catch (error) {
// Custom error handling
if (error.message.includes('404')) {
// Handle 404
} else {
// Handle other errors
}
}
---Note: Only use direct client methods when you need custom error handling. For most cases, use helper functions.
Cache Management
// Clear cache
client.clearCache();
// Get cache statistics
const stats = client.getCacheStats();
console.log(`Cache has ${stats.entries} entries`);CLI Tool
The package includes a powerful CLI for testing and debugging:
npx more-apartments properties list --city Amsterdam
npx more-apartments properties show apartment-slugSee CLI Documentation for full reference.
Documentation
- Examples - Working code examples
- CLI Usage - Command-line interface
- Advanced Usage - Custom error handling, components
- API Methods - Complete API reference
- Security - Security best practices
Contributing
Contributions are welcome! Please feel free to submit a Pull Request.
License
MIT
