consider this function : export const… · The Chat Archive
Explore amazon-nova-experimental-chat-05-14 · Amazon LMArena Human Preference 140Kconsider this function : export const getDashboardAnalyticsData = async (filters: {… Save Share Download ▾ ReportFrom a Chatbot Arena battle The same person sent this prompt to two anonymous models at once. Compare it with qwen3-235b-a22b-no-thinking ’s answer. Copy first prompt
Other models, same or similar prompt Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
Details Model amazon-nova-experimental-chat-05-14Provider Amazon
Model provenance As recorded by source dataset
Turns 2 (4 messages)
Language en
Added to archive Nov 16, 2026
ID 01m7jf8fczxv9cgty2d6yqs0xcSource & license Imported from LMArena Human Preference 140K (source ). Imported records earn no Research Points.
Upstream record: 45e8a9b2-03f9-4754-bb6b-2cebf6894cd2:a
Chiang et al., Chatbot Arena: An Open Platform for Evaluating LLMs by Human Preference (2024). LMArena 140K preference release.
License: Prompts CC-BY-4.0; outputs governed by provider terms
Dataset releases Not yet included in a published release.
consider this function :
export const getDashboardAnalyticsData = async (filters: {
vehicleType?: string;
vehicleState?: string;
}) => {
// Get filtered deviceIds from DB
const filteredDevices = await getFilteredVehicleDeviceIds(filters);
const validDeviceIds = new Set(filteredDevices.map(d => d.deviceId));
const [
modeData,
recentIgnitionData,
historicalIgnitionData,
] = await Promise.all([
getVehicleModesFromVM(),
getLatestIgnitionStatus(),
getLatestIgnitionAcrossTime(),
]);
// === Active Vehicles ===
const latestIgnitionByDevice = new Map<string, { ignition: number; timestamp: number }>();
for (const { deviceId, ignition, timestamp } of recentIgnitionData) {
if (!validDeviceIds.has(deviceId)) continue;
const existing = latestIgnitionByDevice.get(deviceId);
if (!existing || timestamp > existing.timestamp) {
latestIgnitionByDevice.set(deviceId, { ignition, timestamp });
}
}
// === Idle & Parked Vehicles ===
const latestModeByDevice = new Map<string, { value: number; timestamp: number }>();
for (const { deviceId, value, timestamp } of modeData) {
if (!validDeviceIds.has(deviceId)) continue;
const existing = latestModeByDevice.get(deviceId);
if (!existing || timestamp > existing.timestamp) {
latestModeByDevice.set(deviceId, { value, timestamp });
}
}
// === Out of Service Vehicles ===
const now = Math.floor(Date.now() / 1000);
const oneWeekAgo = now - 7 * 24 * 60 * 60;
const latestHistoricalIgnitionByDevice = new Map<string, number>();
for (const { deviceId, timestamp } of historicalIgnitionData) {
if (!validDeviceIds.has(deviceId)) continue;
const existing = latestHistoricalIgnitionByDevice.get(deviceId);
if (!existing || timestamp > existing) {
latestHistoricalIgnitionByDevice.set(deviceId, timestamp);
}
}
const outOfServiceDeviceIds: string[] = [];
for (const [deviceId, timestamp] of latestHistoricalIgnitionByDevice.entries()) {
if (timestamp < oneWeekAgo) {
outOfServiceDeviceIds.push(deviceId);
}
}
await redisClient.setEx('outOfService:vehicles', 3600, JSON.stringify(outOfServiceDeviceIds));
// === Service Due Vehicles ===
const serviceDueDeviceIds = await getServiceDueDevicesFromVM(validDeviceIds);
await redisClient.setEx('serviceDue:vehicles', 900, JSON.stringify(serviceDueDeviceIds));
// === Count by State ===
let active = 0;
let idle = 0;
let parked = 0;
for (const { ignition } of latestIgnitionByDevice.values()) {
if (ignition === 1) active++;
}
for (const { value } of latestModeByDevice.values()) {
if (value === 1) idle++;
else if (value === 0) parked++;
}
return {
totalVehicles: validDeviceIds.size,
activeVehicles: active,
idleVehicles: idle,
parkedVehicles: parked,
outOfServiceVehicles: outOfServiceDeviceIds.length,
serviceDueVehicles: serviceDueDeviceIds.length,
};
};
here for the out of service vehicle we have to store the exact vehicles which are in out of service in redis to later know exactly which devices right now are in out of service.
AssistantCopy response Certainly! Let's break down and improve the getDashboardAnalyticsData function to ensure that it correctly identifies and stores out-of-service vehicles in Redis. We'll also ensure that the function is efficient and easy to understand. Here's the improved version with comments explaining each step:
export const getDashboardAnalyticsData = async (filters: {
vehicleType?: string;
vehicleState?: string;
}) => {
// Step 1: Get filtered device IDs from the database based on the provided filters
const filteredDevices = await getFilteredVehicleDeviceIds(filters);
const validDeviceIds = new Set(filteredDevices.map(d => d.deviceId));
// Step 2: Fetch necessary data in parallel for efficiency
const [
modeData,
recentIgnitionData,
historicalIgnitionData,
] = await Promise.all([
getVehicleModesFromVM(),
getLatestIgnitionStatus(),
getLatestIgnitionAcrossTime(),
]);
// === Active Vehicles ===
const latestIgnitionByDevice = new Map<string, { ignition: number; timestamp: number }>();
for (const { deviceId, ignition, timestamp } of recentIgnitionData) {
if (!validDeviceIds.has(deviceId)) continue; // Skip if deviceId is not in the valid list
const existing = latestIgnitionByDevice.get(deviceId);
if (!existing || timestamp > existing.timestamp) {
latestIgnitionByDevice.set(deviceId, { ignition, timestamp });
}
}
// === Idle & Parked Vehicles ===
const latestModeByDevice = new Map<string, { value: number; timestamp: number }>();
for (const { deviceId, value, timestamp } of modeData) {
if (!validDeviceIds.has(deviceId)) continue; // Skip if deviceId is not in the valid list
const existing = latestModeByDevice.get(deviceId);
if (!existing || timestamp > existing.timestamp) {
latestModeByDevice.set(deviceId, { value, timestamp });
}
}
// === Out of Service Vehicles ===
const now = Math.floor(Date.now() / 1000);
const oneWeekAgo = now - 7 * 24 * 60 * 60; // One week in seconds
const latestHistoricalIgnitionByDevice = new Map<string, number>();
for (const { deviceId, timestamp } of historicalIgnitionData) {
if (!validDeviceIds.has(deviceId)) continue; // Skip if deviceId is not in the valid list
const existing = latestHistoricalIgnitionByDevice.get(deviceId);
if (!existing || timestamp > existing) {
latestHistoricalIgnitionByDevice.set(deviceId, timestamp);
}
}
const outOfServiceDeviceIds: string[] = [];
for (const [deviceId, timestamp] of latestHistoricalIgnitionByDevice.entries()) {
if (timestamp < oneWeekAgo) {
outOfServiceDeviceIds.push(deviceId);
}
}
// Store the out-of-service device IDs in Redis with a 1-hour expiration
await redisClient.setEx('outOfService:vehicles', 3600, JSON.stringify(outOfServiceDeviceIds));
// === Service Due Vehicles ===
const serviceDueDeviceIds = await getServiceDueDevicesFromVM(validDeviceIds);
// Store the service-due device IDs in Redis with a 15-minute expiration
await redisClient.setEx('serviceDue:vehicles', 900, JSON.stringify(serviceDueDeviceIds));
// === Count by State ===
let active = 0;
let idle = 0;
let parked = 0;
// Count active vehicles
for (const { ignition } of latestIgnitionByDevice.values()) {
if (ignition === 1) active++;
}
// Count idle and parked vehicles
for (const { value } of latestModeByDevice.values()) {
if (value === 1) idle++;
else if (value === 0) parked++;
}
// Return the analytics data
return {
totalVehicles: validDeviceIds.size,
activeVehicles: active,
idleVehicles: idle,
parkedVehicles: parked,
outOfServiceVehicles: outOfServiceDeviceIds.length,
serviceDueVehicles: serviceDueDeviceIds.length,
};
};
in these routes :
import { Router } from "express";
import { createProfile, getProfileByTcu, getAllProfiles, createProfileBAU, updateVehicleProfile, deleteVehicleProfile } from "../controllers/vehicleProfile.controller";
const router = Router();
router.post("/", createProfile);
router.delete("/delete", deleteVehicleProfile);
router.get("/", getAllProfiles);
router.post("/bau", createProfileBAU);
router.put("/update", updateVehicleProfile);
router.get("/:ownerMail", getProfileByTcu);
router.get("/outOfService", getOutOfServiceVehicles);
export default router;
controller :
import { Request, Response } from "express";
import {
addBauVehicleProfile,
addVehicleProfile,
fetchVehicleProfile,
listVehicleProfiles,
updateProfile,
deleteVehicleProfileByTCUId
} from "../services/vehicleProfile.service";
export const createProfile = async (req: Request, res: Response) => {
try {
const profile = await addVehicleProfile(req.body);
return res.status(201).json({
message: "Vehicle profile created successfully",
status: "success",
result: profile,
});
} catch (error: any) {
console.log(error);
return res.status(400).json({
message: error.message ?? "Failed to create vehicle profile",
status: "failed",
});
}
};
export const getProfileByTcu = async (req: Request, res: Response) => {
try {
const { ownerMail } = req.params;
const profile = await fetchVehicleProfile(ownerMail);
if (!profile) {
return res.status(404).json({
message: "Vehicle profile not found",
status: "failed",
});
}
return res.status(200).json({
message: "Vehicle profile fetched successfully",
status: "success",
result: profile,
});
} catch (error: any) {
return res.status(500).json({
message: error.message ?? "Error fetching vehicle profile",
status: "failed",
});
}
};
export const getAllProfiles = async (_req: Request, res: Response) => {
try {
const { page = 1, limit = 10, vehicleType, city, search } = _req.query;
const { profiles, total } = await listVehicleProfiles({
page: Number(page),
limit: Number(limit),
vehicleType: vehicleType as string,
city: city as string,
search: search as string,
});
return res.status(200).json({
profiles,
total,
totalPages: Math.ceil(total / Number(limit)),
currentPage: Number(page),
limit: Number(limit),
});
} catch (error: any) {
return res.status(500).json({
message: error.message ?? "Error fetching vehicle profiles",
status: "failed",
});
}
};
export const createProfileBAU = async (req: Request, res: Response) => {
try {
const profile = await addBauVehicleProfile(req.body);
return res.status(201).json({
message: "Vehicle profile created successfully",
status: "success",
result: profile,
});
} catch (error: any) {
console.log(error);
return res.status(400).json({
message: error.message ?? "Failed to create vehicle profile",
status: "failed",
});
}
};
export const updateVehicleProfile = async (req: Request, res: Response) => {
try {
const profile = await updateProfile(req.body);
return res.status(201).json({
message: "Vehicle profile created successfully",
status: "success",
result: profile,
});
} catch (error: any) {
console.log(error);
return res.status(400).json({
message: error.message ?? "Failed to create vehicle profile",
status: "failed",
});
}
};
AssistantCopy response Certainly! To create an API endpoint that retrieves out-of-service vehicles using the device IDs stored in Redis, you need to follow these steps:
Fetch the out-of-service device IDs from Redis.
Use these device IDs to query the vehicle profiles from the database.
Return the vehicle profiles in the response.
Here's how you can implement the getOutOfServiceVehicles controller and add the corresponding route.
Step 1: Update the Controller
Add the getOutOfServiceVehicles function to the vehicleProfile.controller.ts file.
import { Request, Response } from "express";
import redisClient from "../config/redis.config"; // Make sure to import your Redis client configuration
import { getVehicleProfileByTcuId } from "../services/vehicleProfile.service";
export const getOutOfServiceVehicles = async (_req: Request, res: Response) => {
try {
// Fetch the out-of-service device IDs from Redis
const outOfServiceDeviceIdsJson = await redisClient.get('outOfService:vehicles');
if (!outOfServiceDeviceIdsJson) {
return res.status(404).json({
message: "No out-of-service vehicles found",
status: "failed",
});
}
const outOfServiceDeviceIds: string[] = JSON.parse(outOfServiceDeviceIdsJson);
// Fetch vehicle profiles for the out-of-service device IDs
const outOfServiceVehicles = await Promise.all(
outOfServiceDeviceIds.map((deviceId) => getVehicleProfileByTcuId(deviceId))
);
// Filter out any null results (in case a device ID does not have a corresponding profile)
const validOutOfServiceVehicles = outOfServiceVehicles.filter((profile): profile is IVehicleProfile => profile !== null);
return res.status(200).json({
message: "Out-of-service vehicles fetched successfully",
status: "success",
result: validOutOfServiceVehicles,
});
} catch (error: any) {
return res.status(500).json({
message: error.message ?? "Error fetching out-of-service vehicles",
status: "failed",
});
}
};
Step 2: Update the Routes
Add the new route to the vehicleProfile.routes.ts file.
import { Router } from "express";
import {
createProfile,
getProfileByTcu,
getAllProfiles,
createProfileBAU,
updateVehicleProfile,
deleteVehicleProfile,
getOutOfServiceVehicles // Import the new controller function
} from "../controllers/vehicleProfile.controller";
const router = Router();
router.post("/", createProfile);
router.delete("/delete", deleteVehicleProfile);
router.get("/", getAllProfiles);
router.post("/bau", createProfileBAU);
router.put("/update", updateVehicleProfile);
router.get("/:ownerMail", getProfileByTcu);
router.get("/outOfService", getOutOfServiceVehicles); // Add the new route
export default router;
Copy first response
Explanation:
Filtering Device IDs:
getFilteredVehicleDeviceIds(filters) fetches the device IDs that match the provided filters.
validDeviceIds is a set of these device IDs for quick lookups.
Parallel Data Fetching:
Promise.all is used to fetch modeData, recentIgnitionData, and historicalIgnitionData in parallel, improving efficiency.
Active Vehicles:
latestIgnitionByDevice maps each device ID to its latest ignition status and timestamp.
Only devices in validDeviceIds are considered.
If a newer timestamp is found for a device, it updates the map.
Idle & Parked Vehicles:
latestModeByDevice maps each device ID to its latest mode (idle or parked) and timestamp.
Only devices in validDeviceIds are considered.
If a newer timestamp is found for a device, it updates the map.
Out of Service Vehicles:
latestHistoricalIgnitionByDevice maps each device ID to the timestamp of its latest ignition event.
Only devices in validDeviceIds are considered.
If a newer timestamp is found for a device it updates the map.
Devices with a timestamp older than one week are considered out of service.
outOfServiceDeviceIds stores the device IDs of out-of-service vehicles.
These IDs are stored in Redis with a key outOfService:vehicles and an expiration time of 1 hour.
Service Due Vehicles:
getServiceDueDevicesFromVM(validDeviceIds) fetches the device IDs of vehicles due for service.
These IDs are stored in Redis with a key serviceDue:vehicles and an expiration time of 15 minutes.
Counting Vehicle States:
active, idle, and parked counters are initialised to zero.
The function iterates over the values in latestIgnitionByDevice to count active vehicles.
It iterates over the values in latestModeByDevice to count idle and parked vehicles.
Returning Analytics Data:
The function returns an object with counts of total, active, idle, parked, out-of-service, and service-due vehicles.
This function ensures that out-of-service vehicle IDs are accurately identified and stored in Redis for later retrieval.
export const deleteVehicleProfile = async (req: Request, res: Response) => {
try {
const tcuId = req.query.tcuId as string;
if (!tcuId) {
return res.status(400).json({
message: "TCU ID is required",
status: "failed",
});
}
const result = await deleteVehicleProfileByTCUId(tcuId);
return res.status(200).json({
message: "Vehicle profile deleted successfully",
status: "success",
result
});
} catch (error: any) {
return res.status(400).json({
message: error.message ?? "Failed to delete vehicle profile",
status: "failed",
});
}
};
services :
import { createVehicleProfile, getVehicleProfileByTcuId, getAllVehicleProfiles, createBauVehicleProfile, updateVehicleProfile, updateVPEmergencyContacts, getVehicleProfileByOwnerMail, deleteVehicleProfileByTcuId } from "../repositories/vehicleProfile.repository";
import { findDeviceByTcuId, unprovisionDeviceByTcuId, updateDeviceByTcuId } from "../repositories/device.repository";
import { deleteMobileUserByEmail, findMobileUserByEmail, updateMobileUserByEmail } from "../repositories/mobileUser.repository";
import { IVehicleProfile } from "../models/vehicleProfile.model";
import { produceDeviceProvisioningEvent } from "../events/producers/device.producer";
import { produceUserCreatedEvent } from "../events/producers/user.producer";
import { IMobileUser } from "../models/mobileUser.model";
export const addVehicleProfile = async (data: Partial) => {
const { ownerMail, tcuId } = data;
const user = await findMobileUserByEmail(ownerMail);
if (!user) {
throw new Error(User not found with email: ${ownerMail});
}
const device = await findDeviceByTcuId(tcuId);
if (!device) {
throw new Error(Device not found with TCU ID: ${tcuId});
}
const existingProfile = await getVehicleProfileByTcuId(tcuId);
if (existingProfile) {
throw new Error(Vehicle profile already exists for TCU ID: ${tcuId});
}
await updateDeviceByTcuId(tcuId, {
isProvisioned: true,
})
await updateMobileUserByEmail(ownerMail, {
vehicleRegistered: true,
});
return await createVehicleProfile({ ...data, manufacturingYear: device.manufacturingYear, tcuModel: device.modelNumber, iemiNumber: device.imeiNumber, softwareVersion: device.firmwareVersion });
};
export const fetchVehicleProfile = async (ownerMail: string) => {
return await getVehicleProfileByOwnerMail(ownerMail);
};
export const listVehicleProfiles = async (options: {
page?: number;
limit?: number;
vehicleType?: string;
city?: string;
search?: string;
}) => {
const { page = 1, limit = 10, vehicleType, city, search } = options;
const { profiles, total } = await getAllVehicleProfiles({
page,
limit,
vehicleType,
city,
search,
});
return {
profiles,
total,
};
};
export const addBauVehicleProfile = async (data: Partial) => {
const { tcuId, ownerMail } = data;
if (!tcuId || !ownerMail) {
throw new Error("tcuId and ownerMail are required.");
}
const existingProfile = await getVehicleProfileByTcuId(tcuId);
const existingUser = await findMobileUserByEmail(ownerMail);
const device = await findDeviceByTcuId(tcuId);
if (existingUser) {
throw new Error(User already exists with email: ${ownerMail});
}
if (existingProfile) {
throw new Error(Vehicle profile already exists for TCU ID: ${tcuId});
}
// Create vehicle profile locally
// Fire event to Device Service
await produceDeviceProvisioningEvent({ tcuId, isProvisioned: true });
// Fire event to User Service
await produceUserCreatedEvent({
email: data.ownerMail,
name: data.ownerName,
mobileNumber: data.contactNumber,
city: "",
state: "",
source: data.provisionSource,
});
const profile = await createBauVehicleProfile({ ...data, manufacturingYear: device.manufacturingYear, iemiNumber: device.imeiNumber, softwareVersion: device.firmwareVersion });
export const updateProfile = async (data: Partial) => {
const { tcuId } = data;
if (!tcuId) {
throw new Error("tcuId is required.");
}
return await updateVehicleProfile(tcuId, data);
};
export const updateEmergencyContacts = async (data: any) => {
const { ownerMail, emergencyContact } = data;
const result = await updateVPEmergencyContacts(ownerMail, emergencyContact);
if (result) {
console.log(Emergency contacts updated for vehicle profile of owner: ${ownerMail});
}
}
export const updateVehicleProfileAfterUserUpdate = async (data: IMobileUser) => {
const { email, name, mobileNumber, city, state, postalCode, documents } = data;
console.log(email);
const profile = await getVehicleProfileByOwnerMail(email); // assumes email is stored as ownerMail
if (!profile) {
console.warn(No vehicle profile found for user email: ${email});
return;
}
const updatedFields: Partial = {
ownerName: name,
contactNumber: mobileNumber,
document: documents || [],
...(city && { city }),
...(state && { state }),
...(postalCode && { postalCode }),
};
await updateVehicleProfile(profile.tcuId, updatedFields);
console.log(Vehicle profile updated for user email: ${email});
};
export const deleteVehicleProfileByTCUId = async (tcuId: string) => {
if (!tcuId) {
throw new Error("TCU ID is required to delete vehicle profile.");
}
const profile = await getVehicleProfileByTcuId(tcuId);
if (!profile) {
throw new Error(No vehicle profile found for TCU ID: ${tcuId});
}
await deleteVehicleProfileByTcuId(tcuId);
await unprovisionDeviceByTcuId(tcuId);
await deleteMobileUserByEmail(profile.ownerMail);
console.log(Vehicle profile with TCU ID: ${tcuId} deleted successfully.);
return profile;
}
repository :
import { VehicleProfileModel, IVehicleProfile } from "../models/vehicleProfile.model";
import { AnonymizedVehicleProfileModel } from "../models/vehicleProfile.model";
export const createVehicleProfile = async (data: Partial): Promise => {
return VehicleProfileModel().create(data);
};
export const createAnonymizedVehicleProfile = async (data: Partial): Promise => {
return AnonymizedVehicleProfileModel().create(data);
};
export const deleteVehicleProfileByOwnerMail = async (oldEmail: string): Promise => {
await VehicleProfileModel().deleteOne({ ownerMail: oldEmail });
};
export const createBauVehicleProfile = async (data: Partial): Promise => {
return VehicleProfileModel().create(data);
};
export const getVehicleProfileByTcuId = async (tcuId: string): Promise<IVehicleProfile | null> => {
return VehicleProfileModel().findOne({ tcuId });
};
export const getVehicleProfileByOwnerMail = async (ownerMail: string): Promise<IVehicleProfile | null> => {
return VehicleProfileModel().findOne({ ownerMail });
};
export const getVehicleProfileByVin = async (vin: string): Promise<IVehicleProfile | null> => {
return VehicleProfileModel().findOne({ vin });
};
export const getAllVehicleProfiles = async (options: {
page?: number;
limit?: number;
vehicleType?: string;
city?: string;
search?: string;
}): Promise<{ profiles: IVehicleProfile[]; total: number }> => {
const { page = 1, limit = 10, vehicleType, city, search } = options;
const filters: Record<string, any> = {};
if (vehicleType) filters.vehicleType = vehicleType;
if (city) filters.city = city;
if (search) filters.tcuId = { r e g e x : s e a r c h , regex: search, r e g e x : se a r c h , options: "i" };
const total = await VehicleProfileModel().countDocuments(filters);
const profiles = await VehicleProfileModel().find(filters).sort({ createdAt: -1 }).skip((page - 1) * limit).limit(limit);
return { profiles, total };
};
export const updateVehicleProfile = async (tcuId: string, updates: Partial): Promise<IVehicleProfile | null> => {
return VehicleProfileModel().findOneAndUpdate({ tcuId }, updates, { new: true });
};
export const updateVehicleProfileByOwnerMail = async (ownerMail: string, updates: Partial): Promise<IVehicleProfile | null> => {
return VehicleProfileModel().findOneAndUpdate({ ownerMail }, updates, { new: true });
};
export const updateVPEmergencyContacts = async (ownerMail: string, emergencyContacts: any): Promise<IVehicleProfile | null> => {
return VehicleProfileModel().findOneAndUpdate({ ownerMail }, { emergencyContact: emergencyContacts }, { new: true });
};
export const deleteVehicleProfileByTcuId = async (tcuId: string): Promise<IVehicleProfile | null> => {
return VehicleProfileModel().findOneAndDelete({ tcuId });
};
we have to give the api for out of service vehicles by taking the device id from redis and use it here to find the vehicle profiles with the same tcuID:
import { Schema, Document, Model } from "mongoose";
import { getDBConnection } from "../config/db.config";
export interface IVehicleProfile extends Document {
registrationNumber: string;
ownerName: string;
ownerMail: string;
emergencyContact?: {};
contactNumber?: string;
registrationDate?: Date;
chassisNumber: string;
vin: string;
clusterId?: string;
batteryId?: string;
tcuId: string;
tcuProvisioningDate: Date;
mcuId?: string;
vehicleModel?: string;
tcuModel?: string;
provisionSource?: "after_market" | "business_as_usual";
provisioningStatus?: string;
city?: string;
status?: string;
state?: string;
vehicleImage?: string;
vehicleType?: string;
purchaseDate?: Date;
manufacturingYear?: Date;
dob?: Date;
iemiNumber?: string;
softwareVersion?: string;
tcuModelNumber?: string;
document?: string[];
}
const schema = new Schema(
{
registrationNumber: { type: String, required: true },
ownerMail: { type: String, required: true },
ownerName: { type: String, required: true },
emergencyContact: {
type: {},
default: {},
required: false,
}, // Only BAU
contactNumber: { type: String }, // Only After Market
registrationDate: { type: Date }, // Only BAU
chassisNumber: { type: String, required: true },
vin: { type: String, required: true },
clusterId: { type: String },
batteryId: { type: String },
tcuId: { type: String, required: true },
tcuProvisioningDate: { type: Date, default: Date.now },
mcuId: { type: String },
vehicleModel: { type: String }, // Only BAU
tcuModel: { type: String }, // Only After Market
provisionSource: {
type: String,
enum: ["after_market", "business_as_usual"]
},
provisioningStatus: { type: String, default: "pending" },
city: { type: String },
status: { type: String },
state: { type: String },
vehicleImage: { type: String },
vehicleType: { type: String },
purchaseDate: { type: Date },
manufacturingYear: { type: Date },
dob: { type: Date },
iemiNumber: { type: String },
softwareVersion: { type: String },
tcuModelNumber: { type: String },
document: { type: [String], default: [], required: false }
},
{ timestamps: true }
);
export const VehicleProfileModel = (): Model => {
const conn = getDBConnection("vehicleProfile");
return conn.models.VehicleProfile || conn.model("VehicleProfile", schema);
};
export const AnonymizedVehicleProfileModel = (): Model => {
const conn = getDBConnection("vehicleProfile");
return conn.models.AnonymizedVehicleProfile || conn.model("AnonymizedVehicleProfile", schema, 'anonymized_vehicleprofiles');
};
Step 3: Ensure Redis Configuration Make sure your Redis client is properly configured. Here is an example of a basic Redis configuration (redis.config.ts):
import redis from "redis";
const redisClient = redis.createClient({
host: process.env.REDIS_HOST || 'localhost',
port: Number(process.env.REDIS_PORT) || 6379,
});
redisClient.on("error", (error) => {
console.error("Redis error:", error);
});
export default redisClient;
Explanation
Fetching Device IDs from Redis:
The getOutOfServiceVehicles function fetches the out-of-service device IDs from Redis using the key outOfService:vehicles.
If no device IDs are found, it returns a 404 response.
Querying Vehicle Profiles:
It uses the getVehicleProfileByTcuId service function to fetch the vehicle profiles for each out-of-service device ID.
Promise.all is used to fetch all profiles in parallel for efficiency.
Filtering and Returning Results:
The function filters out any null results (in case a device ID does not have a corresponding profile).
It returns the list of out-of-service vehicle profiles in the response.
With these changes, you now have an API endpoint at GET /outOfService that returns the profiles of out-of-service vehicles.