Skip to content

Commit

Permalink
Bugfixed date casting to de-timezone when returning from the database…
Browse files Browse the repository at this point in the history
…, updated version for release
  • Loading branch information
theianjohnson committed Nov 26, 2023
1 parent b124931 commit 905253d
Show file tree
Hide file tree
Showing 6 changed files with 57 additions and 14 deletions.
2 changes: 1 addition & 1 deletion dist/Model.js
Original file line number Diff line number Diff line change
Expand Up @@ -215,7 +215,7 @@ class Model {
case 'string':
return String(value);
case 'date':
return !!value ? new Date(value) : null;
return !!value ? new Date(new Date(value).toISOString().replace('Z', '')) : null;
case 'datetime':
return !!value ? new Date(value) : null;
case 'json':
Expand Down
2 changes: 1 addition & 1 deletion dist/Model.js.map

Large diffs are not rendered by default.

36 changes: 35 additions & 1 deletion example/App.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,13 @@ import { Button, StyleSheet, Text, View } from 'react-native';
import { Model, Migration } from './local-version-of-expo-sqlite-eloquent-orm';

// Define some models
class Event extends Model {
static casts = {
startDate: 'date',
endDate: 'date',
};
}

class Group extends Model {
static withTimestamps = false;

Expand Down Expand Up @@ -37,6 +44,17 @@ class Person extends Model {

// Define migrations
const migrations = {
'1699142746_init_events': `
CREATE TABLE IF NOT EXISTS events (
id INTEGER PRIMARY KEY NOT NULL,
createdAt DATETIME NOT NULL,
updatedAt DATETIME NOT NULL,
name TEXT,
startDate DATE,
endDate DATE,
notes TEXT
);
`,
'1699142747_init_groups': `
CREATE TABLE IF NOT EXISTS groups (
id INTEGER PRIMARY KEY NOT NULL,
Expand Down Expand Up @@ -72,6 +90,11 @@ const migrations = {

// Seed data
const seedData = {
events: [
{ id: 1, name: 'Birthday Party', startDate: '2024-10-01', notes: 'Bring a gift!' },
{ id: 2, name: 'Wedding', startDate: '2025-01-01', endDate: '2025-01-01' },
{ id: 3, name: 'Graduation', startDate: '2025-05-01', endDate: '2025-05-04' },
],
groups: [
{ id: 1, name: 'Family' },
{ id: 2, name: 'Friends' },
Expand Down Expand Up @@ -99,7 +122,7 @@ const seedData = {

export default function App() {

// const [groups, setGroups] = useState([]);
const [events, setEvents] = useState([]);
const [location, setLocation] = useState(null);
const [locations, setLocations] = useState([]);
const [people, setPeople] = useState([]);
Expand All @@ -120,6 +143,9 @@ export default function App() {
// Run whenever we trigger rerender so we can see what deleting and recreating the database does
useEffect(() => {
(async() => {
const events = await Event.get();
setEvents(events);

const location = await Location.with('people').find(1);
setLocation(location);

Expand All @@ -144,6 +170,7 @@ export default function App() {
}

const seedDatabase = async () => {
await Event.seed(seedData.events);
await Group.seed(seedData.groups);
await Location.seed(seedData.locations);
await Person.seed(seedData.people);
Expand All @@ -156,6 +183,13 @@ export default function App() {

return (
<View style={styles.container}>
<Text>Events:</Text>
{!!events.length && events.map(event => (
<Text key={event.id}>{event.name} - {Intl.DateTimeFormat(undefined).format(event.startDate)} {!!event.endDate ? `to ${Intl.DateTimeFormat(undefined).format(event.endDate)}` : ''}</Text>
))}

<View style={{ height: 10 }} />

<Text>Location:</Text>
{!!location && (
<Text>{location.name} - {!!location?.people?.length && location.people.map(person => person.name).join(', ')}</Text>
Expand Down
27 changes: 18 additions & 9 deletions example/local-version-of-expo-sqlite-eloquent-orm/Model.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import * as SQLite from 'expo-sqlite'

type Casts = {[key: string]: 'number' | 'boolean' | 'string' | 'date' | 'json'}
type Casts = {[key: string]: 'number' | 'boolean' | 'string' | 'date' | 'datetime' | 'json'}

type Clauses = {
select: string
Expand All @@ -11,7 +11,7 @@ type Clauses = {
secondKey: string
}>
where: Array<{ column: string, operator: string, value?: any }>
orderBy: { column: string, direction: string } | null
orderBy: Array<{ column: string, direction: string }>
limit: number | null
withRelations: string[]
}
Expand All @@ -34,8 +34,8 @@ export class Model {
static tableName = ''

static casts: Casts = {
createdAt: 'date',
updatedAt: 'date',
createdAt: 'datetime',
updatedAt: 'datetime',
}

static withTimestamps: boolean = true;
Expand All @@ -55,7 +55,7 @@ export class Model {
select: '*',
joins: [],
where: [],
orderBy: null,
orderBy: [],
limit: null,
withRelations: []
}
Expand Down Expand Up @@ -85,6 +85,7 @@ export class Model {
static async resetDatabase() {
await this.db.closeAsync();
await this.db.deleteAsync();
// @ts-ignore
this.db = null;
this.db = SQLite.openDatabase('app.db');
}
Expand Down Expand Up @@ -216,6 +217,8 @@ export class Model {
case 'string':
return String(value);
case 'date':
return !!value ? new Date((new Date(value).toISOString()).replace('Z', '')) : null;
case 'datetime':
return !!value ? new Date(value) : null;
case 'json':
try {
Expand All @@ -240,7 +243,9 @@ export class Model {
case 'string':
return String(value);
case 'date':
return value instanceof Date ? value.toISOString() : value;
return value instanceof Date ? value.toISOString().split('T')[0] : (new Date(value)).toISOString().split('T')[0];
case 'datetime':
return value instanceof Date ? value.toISOString() : (new Date(value)).toISOString();
case 'json':
try {
return JSON.stringify(value);
Expand Down Expand Up @@ -278,7 +283,7 @@ export class Model {
}

orderBy (column: string, direction: 'ASC' | 'DESC' = 'ASC'): this {
this.__private.clauses.orderBy = { column, direction }
this.__private.clauses.orderBy.push({ column, direction })
return this
}

Expand Down Expand Up @@ -400,8 +405,12 @@ export class Model {
}

// Add ORDER BY clause if set
if (this.__private.clauses.orderBy) {
query += ` ORDER BY ${this.clauses.orderBy.column} ${this.clauses.orderBy.direction}`
if (this.__private.clauses.orderBy.length > 0) {
const orderByClauses = this.__private.clauses.orderBy.map(clause => {
return `${clause.column} ${clause.direction}`
}).join(', ')

query += ` ORDER BY ${orderByClauses}`
}

// Add LIMIT clause if set
Expand Down
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "expo-sqlite-eloquent-orm",
"version": "0.9.19",
"version": "0.9.20",
"description": "An Expo SQLite ORM",
"main": "dist/index.js",
"types": "dist/index.d.ts",
Expand Down
2 changes: 1 addition & 1 deletion src/Model.ts
Original file line number Diff line number Diff line change
Expand Up @@ -217,7 +217,7 @@ export class Model {
case 'string':
return String(value);
case 'date':
return !!value ? new Date(value) : null;
return !!value ? new Date((new Date(value).toISOString()).replace('Z', '')) : null;
case 'datetime':
return !!value ? new Date(value) : null;
case 'json':
Expand Down

0 comments on commit 905253d

Please sign in to comment.