MoodyApi 1.0.2
dotnet add package MoodyApi --version 1.0.2
NuGet\Install-Package MoodyApi -Version 1.0.2
<PackageReference Include="MoodyApi" Version="1.0.2" />
<PackageVersion Include="MoodyApi" Version="1.0.2" />
<PackageReference Include="MoodyApi" />
paket add MoodyApi --version 1.0.2
#r "nuget: MoodyApi, 1.0.2"
#:package MoodyApi@1.0.2
#addin nuget:?package=MoodyApi&version=1.0.2
#tool nuget:?package=MoodyApi&version=1.0.2
MoodyApi π
Tired of boring, robotic API responses?
MoodyApi adds personality to your .NET applications by wrapping your responses with mood-based messages β tailored to user behavior, system context, and even time of day.
Why MoodyApi? π€
In a world full of lifeless JSON, MoodyApi brings your APIs to life with responses that can be:
- π― Personalized β Based on user activity and karma tracking
- β° Context-aware β Adjusts mood based on time of day or system state
- π Engaging β Injects humor, motivation, or sarcasm depending on your settings
- π‘οΈ Graceful under pressure β Handles errors with style
- π§ Lightweight and pluggable β Easy to drop into any ASP.NET Core pipeline
About This Project π§ͺ
This is my first NuGet package β created as a simple, developer-focused library that adds fun and context to your API responses.
Itβs lightweight, easy to integrate, and open to extension.
Think of it as middleware with a personality.
Ready to give your APIs some attitude? Let's go!
Table of Contents
- Features
- Installation
- Quick Start
- Usage Examples
- ASP.NET Core Middleware
- Configuration
- Mood Types
- Advanced Usage
- Best Practices
- Contributing
- License
Features β¨
- π 6 Built-in Mood Types: Neutral, Motivational, Sarcastic, Karma-Based, Time-Based, Error-Based
- ποΈ Extensible Architecture: Easily add custom mood providers
- π€ User Karma Tracking: Personalize responses based on user activity
- β‘ High Performance: Optimized for production use with automatic cleanup
- π§ Flexible Configuration: Configure via DI, appsettings.json, or runtime
- π ASP.NET Core Integration: Seamless middleware for automatic response wrapping
- π Comprehensive Logging: Full observability with Microsoft.Extensions.Logging
- π‘οΈ Robust Error Handling: Graceful fallbacks for all scenarios
- π§΅ Thread-Safe: Built for concurrent applications
- π¦ Zero Dependencies: Only uses standard .NET libraries
Installation π¦
Install from NuGet Package Manager:
Install-Package MoodyApi
Or using the .NET CLI:
dotnet add package MoodyApi
Requirements: .NET 6.0 or higher
Quick Start π
1. Basic Setup
using MoodyApi.Extensions;
using MoodyApi.Models;
// Register services
var services = new ServiceCollection();
services.AddLogging();
services.AddMoodyApi();
var serviceProvider = services.BuildServiceProvider();
// Initialize the static API
MoodyApi.Mood.Initialize(serviceProvider);
// Generate your first mood message
string message = MoodyApi.Mood.Get(MoodType.Motivational);
Console.WriteLine(message);
// Output: "You are capable of amazing things."
2. ASP.NET Core Setup
var builder = WebApplication.CreateBuilder(args);
// Add MoodyApi services
builder.Services.AddMoodyApi(options =>
{
options.Mode = MoodType.Sarcastic;
options.KarmaThreshold = 5;
});
var app = builder.Build();
// Initialize and use middleware
MoodyApi.Mood.Initialize(app.Services);
app.UseMoodyApi();
app.MapGet("/hello", () => new { message = "Hello World!" });
app.Run();
Usage Examples π‘
Basic Message Generation
using MoodyApi.Models;
// Get a simple message
string motivational = MoodyApi.Mood.Get(MoodType.Motivational);
string sarcastic = MoodyApi.Mood.Get(MoodType.Sarcastic);
string timeBased = MoodyApi.Mood.Get(MoodType.TimeBased);
Console.WriteLine(motivational);
// Output: "Dream big. Work hard. Stay focused."
Detailed Mood Responses
// Get a complete mood response with metadata
var response = MoodyApi.Mood.GetResponse(MoodType.KarmaBased, userId: "user-123");
Console.WriteLine($"Message: {response.Message}");
Console.WriteLine($"Mood: {response.Mood}");
Console.WriteLine($"Timestamp: {response.Timestamp}");
Console.WriteLine($"Karma Score: {response.KarmaScore}");
// Output:
// Message: "What you seek is also seeking you."
// Mood: KarmaBased
// Timestamp: 2024-01-15 10:30:45
// Karma Score: 3
Time-Based Messages
// Messages automatically adapt to time of day
string morning = MoodyApi.Mood.Get(MoodType.TimeBased);
// Morning (6-12): "Good morning! Ready to start fresh?"
// Afternoon (12-17): "Afternoon productivity in full swing!"
// Evening (17-21): "Evening requests have a special charm."
// Night (21-6): "Burning the midnight oil?"
Error Handling
// MoodyApi gracefully handles errors
try
{
var response = MoodyApi.Mood.GetResponse(MoodType.ErrorBased);
Console.WriteLine(response.Message);
// Output: "Oops! Something went sideways."
}
catch (Exception ex)
{
// MoodyApi handles exceptions internally
// and returns fallback messages
}
ASP.NET Core Middleware π
The middleware automatically wraps your API responses with mood data:
Setup
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddMoodyApi(options =>
{
options.Mode = MoodType.KarmaBased;
options.EnableSarcasm = true;
});
var app = builder.Build();
MoodyApi.Mood.Initialize(app.Services);
app.UseMoodyApi(); // Add this line
app.MapGet("/users", () => new { users = new[] { "Alice", "Bob" } });
app.Run();
Response Format
{
"success": true,
"statusCode": 200,
"data": {
"users": ["Alice", "Bob"]
},
"mood": {
"message": "Your digital footprint creates ripples in the cosmic code.",
"mood": "KarmaBased",
"timestamp": "2024-01-15T10:30:45.123Z",
"karmaScore": 7
}
}
Middleware Configuration
// The middleware automatically skips certain paths
// - Swagger/OpenAPI endpoints
// - Static files (CSS, JS, images)
// - Health check endpoints
// - Non-JSON responses
// You can customize user identification
// Default: Uses X-User-ID header or IP address
Configuration βοΈ
Via Dependency Injection
services.AddMoodyApi(options =>
{
options.Mode = MoodType.Motivational; // Default mood
options.EnableSarcasm = true; // Enable sarcastic responses
options.EnableMotivation = true; // Enable motivational messages
options.EnableKarma = true; // Enable karma tracking
options.EnableTimeBased = true; // Enable time-based messages
options.KarmaThreshold = 5; // Karma threshold for special messages
});
Via appsettings.json
{
"MoodOptions": {
"Mode": "Sarcastic",
"EnableSarcasm": true,
"EnableMotivation": true,
"EnableKarma": true,
"EnableTimeBased": true,
"KarmaThreshold": 10
}
}
// Bind from configuration
var moodOptions = builder.Configuration.GetSection("MoodOptions").Get<MoodOptions>();
builder.Services.AddMoodyApi(options =>
{
options.Mode = moodOptions.Mode;
options.EnableSarcasm = moodOptions.EnableSarcasm;
// ... other properties
});
Mood Types π
Mood Type | Description | Example Message |
---|---|---|
Neutral | Standard, professional responses | "Request processed successfully." |
Motivational | Uplifting, encouraging messages | "You are capable of amazing things." |
Sarcastic | Witty, humorous responses | "Oh great, another API call. I'm thrilled. π" |
KarmaBased | Philosophical, karma-influenced messages | "What you seek is also seeking you." |
TimeBased | Context-aware based on time of day | "Good morning! Ready to start fresh?" |
ErrorBased | Graceful error handling with personality | "Houston, we have a problem... but also a solution." |
Advanced Usage π§
Custom Message Providers
using MoodyApi.Providers;
using MoodyApi.Providers.Interfaces;
using Microsoft.Extensions.Logging;
public class CustomExcitedProvider : BaseProvider
{
private static readonly string[] Messages = new[]
{
"This is AMAZING! π",
"WOW! Absolutely fantastic!",
"I'm so excited I could explode! π₯"
};
public CustomExcitedProvider(ILogger? logger = null) : base(logger) { }
protected override string GetMessageInternal()
{
var index = Random.Shared.Next(Messages.Length);
return Messages[index];
}
}
Register Custom Providers
services.AddMoodyApi();
// Override the provider dictionary
services.AddSingleton<Dictionary<MoodType, IMessageProvider>>(provider =>
{
var logger = provider.GetService<ILogger<MoodEngine>>();
return new Dictionary<MoodType, IMessageProvider>
{
[MoodType.Neutral] = new NeutralProvider(logger),
[MoodType.Motivational] = new CustomExcitedProvider(logger), // Custom provider
[MoodType.Sarcastic] = new SarcasmProvider(logger),
[MoodType.KarmaBased] = new KarmaProvider(logger),
[MoodType.TimeBased] = new TimeBasedProvider(logger),
[MoodType.ErrorBased] = new ErrorBasedProvider(logger)
};
});
Manual Engine Usage
// If you prefer not to use the static API
var moodEngine = serviceProvider.GetRequiredService<MoodEngine>();
var response = moodEngine.GetMoodResponse(MoodType.Motivational, "user-123");
Best Practices π
1. User Identification
// Use consistent user IDs for karma tracking
var response = MoodyApi.Mood.GetResponse(MoodType.KarmaBased, userId: user.Id);
2. Error Handling
// MoodyApi handles exceptions gracefully, but you can add extra logging
try
{
var message = MoodyApi.Mood.Get(MoodType.Sarcastic);
}
catch (InvalidOperationException ex)
{
// This happens if MoodyApi is not initialized
logger.LogError(ex, "MoodyApi not initialized");
}
3. Performance
// Initialize once at startup
MoodyApi.Mood.Initialize(serviceProvider);
// Use throughout application lifecycle
// The library is thread-safe and optimized for concurrent use
4. Middleware Placement
// Place UseMoodyApi() after routing but before endpoints
app.UseRouting();
app.UseMoodyApi();
app.MapControllers();
Performance & Scaling π
- Thread-Safe: All operations are thread-safe
- Memory Efficient: Automatic cleanup of expired user data
- Zero Allocation: Message arrays are pre-allocated
- Concurrent: Uses
ConcurrentDictionary
for user tracking - Lightweight: Minimal overhead per request
Contributing π€
We welcome contributions! Here's how to get started:
- Fork the repository
- Create a feature branch (
git checkout -b feature/amazing-feature
) - Commit your changes (
git commit -m 'Add amazing feature'
) - Push to the branch (
git push origin feature/amazing-feature
) - Open a Pull Request
Development Setup
git clone https://github.com/freecnsz/MoodyApi.git
cd MoodyApi
dotnet restore
dotnet build
dotnet test
License π
This project is licensed under the MIT License. See the LICENSE file for details.
Support π¬
- Issues: GitHub Issues
- Discussions: GitHub Discussions
- Documentation: Wiki
Acknowledgments π
- Built with β€οΈ for the .NET community
- Inspired by the need for more engaging API experiences
- Thanks to all contributors and users
Made with π by freecnsz
Product | Versions Compatible and additional computed target framework versions. |
---|---|
.NET | net6.0 is compatible. net6.0-android was computed. net6.0-ios was computed. net6.0-maccatalyst was computed. net6.0-macos was computed. net6.0-tvos was computed. net6.0-windows was computed. net7.0 was computed. net7.0-android was computed. net7.0-ios was computed. net7.0-maccatalyst was computed. net7.0-macos was computed. net7.0-tvos was computed. net7.0-windows was computed. net8.0 is compatible. net8.0-android was computed. net8.0-browser was computed. net8.0-ios was computed. net8.0-maccatalyst was computed. net8.0-macos was computed. net8.0-tvos was computed. net8.0-windows was computed. net9.0 was computed. net9.0-android was computed. net9.0-browser was computed. net9.0-ios was computed. net9.0-maccatalyst was computed. net9.0-macos was computed. net9.0-tvos was computed. net9.0-windows was computed. net10.0 was computed. net10.0-android was computed. net10.0-browser was computed. net10.0-ios was computed. net10.0-maccatalyst was computed. net10.0-macos was computed. net10.0-tvos was computed. net10.0-windows was computed. |
-
net6.0
- Microsoft.AspNetCore.Http.Abstractions (>= 2.3.0)
- Microsoft.Extensions.DependencyInjection.Abstractions (>= 8.0.0)
- Microsoft.Extensions.Logging (>= 6.0.1)
-
net8.0
- Microsoft.AspNetCore.Http.Abstractions (>= 2.3.0)
- Microsoft.Extensions.DependencyInjection.Abstractions (>= 8.0.0)
- Microsoft.Extensions.Logging (>= 6.0.1)
NuGet packages
This package is not used by any NuGet packages.
GitHub repositories
This package is not used by any popular GitHub repositories.