1- import file from "../api/posts.json" assert { type : "json" } ;
2- const fs = require ( "fs" ) ;
3- const customer =
4- {
5- name : "d Co." ,
6- order_count : 0 ,
7- address : "Po Box City" ,
8- }
1+ import Post from "../models/Post" ;
92
10- function saveJson ( data :any ) {
11- const jsonString = JSON . stringify ( data ) ;
12- fs . writeFile ( "./src/app/api/posts.json" , jsonString , ( err :any ) => {
13- if ( err ) {
14- console . log ( "Error writing file" , err ) ;
15- } else {
16- console . log ( "Successfully wrote file" ) ;
17- }
18- } ) ;
19- }
20-
21-
22-
23- type Post = {
24- id : string ;
25- title : string ;
26- desc : string ;
27- date : any ;
3+ export const getPosts = async ( ) => {
4+ return await Post . findAll ( ) ;
285} ;
296
30- let posts : Post [ ] = file ;
31-
32- export const getPosts = ( ) => posts ;
33- export const addPost = ( post : Post ) => {
34- posts . push ( post ) ;
35- saveJson ( posts )
36- } ;
37- export const deletePost = ( id : string ) => {
38- posts = posts . filter ( ( post ) => post . id !== id ) ;
39- saveJson ( posts )
7+ export const addPost = async ( post : { id : string ; title : string ; desc : string ; date : Date } ) => {
8+ await Post . create ( post ) ;
409} ;
41- export const updatePost = ( id : string , title : string , desc : string ) => {
42- const post = posts . find ( ( post ) => post . id === id ) ;
43-
4410
45- if ( post ) {
46- post . title = title ;
47- post . desc = desc ;
48- saveJson ( posts )
49- } else {
50- throw new Error ( "NO POST FOUND" ) ;
51- }
11+ export const deletePost = async ( id : string ) => {
12+ const deleted = await Post . destroy ( {
13+ where : { id } ,
14+ } ) ;
15+ if ( deleted === 0 ) throw new Error ( "NO POST FOUND" ) ;
5216} ;
5317
54- export const getById = ( id : string ) => {
55- return posts . find ( ( post ) => post . id === id ) ;
18+ export const updatePost = async ( id : string , title : string , desc : string ) => {
19+ const [ updated ] = await Post . update (
20+ { title, desc } ,
21+ {
22+ where : { id } ,
23+ }
24+ ) ;
25+ if ( updated === 0 ) throw new Error ( "NO POST FOUND" ) ;
5626} ;
27+
28+ export const getById = async ( id : string ) => {
29+ const post = await Post . findByPk ( id ) ;
30+ if ( ! post ) throw new Error ( "NO POST FOUND" ) ;
31+ return post ;
32+ } ;
0 commit comments