import { join } from 'path' ; import { logger } from '../utils' ; import { Nuxtent } from '../../types' ; import NuxtentConfig from '../config' ; import { Nuxt } from '../../types/nuxt' ; param { string } permalink param { string } section param { string } buildDir returns { string } const buildPath = ( permalink , section , buildDir ) => { const allButFirstSlash = /(?!^\/)\//g ; const filePath = permalink . replace ( allButFirstSlash , '.' ) ; return join ( buildDir , section , filePath ) + '.json' ; } ; const asset = ( object ) => { const content = JSON . stringify ( object , null , process . env . NODE_ENV === 'production' ? 0 : 2 ) ; return { source : ( ) => content , size : ( ) => content . length } ; } ; export function addAssets ( nuxtOpts , assetMap ) { logger . debug ( 'Adding routes as assets for production' ) ; nuxtOpts . build . plugins . push ( { apply ( compiler ) { compiler . plugin ( 'emit' , ( compilation , cb ) => { assetMap . forEach ( ( page , path ) => { compilation . assets [ path ] = asset ( page ) ; } ) ; cb ( ) ; } ) ; } , } ) ; } param { NuxtentConfig } nuxtentConfig param { Map < any , any > } contentDatabase returns { void } export function createStaticRoutes ( nuxtentConfig ) { const contentDatabase = nuxtentConfig . database ; const content = nuxtentConfig . content ; const buildDir = nuxtentConfig . build . buildDir ; for ( let [ dirName , { page , method } ] of content ) { const db = contentDatabase . get ( dirName ) ; if ( ! db ) { throw new Error ( `Database not found ${ dirName }` ) ; } if ( ! page ) { throw new Error ( 'You must specify a page path ' + dirName ) ; } if ( ! Array . isArray ( method ) ) { method = [ method ] ; } method . forEach ( reqType => { const req = { args : [ ] , method : '' , query : { } , } ; if ( typeof reqType === 'string' ) { req . method = reqType ; } else if ( Array . isArray ( reqType ) ) { const [ reqMethod , reqOptions ] = reqType ; req . args = reqOptions . args || [ ] ; req . method = typeof reqMethod === 'string' ? reqMethod : reqMethod [ 0 ] ; req . query = reqOptions . query ? reqOptions . query : { } ; } switch ( req . method ) { case 'get' : db . findAll ( req . query ) . forEach ( publicPage => { nuxtentConfig . staticRoutes . push ( publicPage . permalink ) ; nuxtentConfig . assetMap . set ( buildPath ( publicPage . permalink , dirName , buildDir ) , publicPage ) ; } ) ; break ; case 'getAll' : nuxtentConfig . assetMap . set ( buildPath ( '_all' , dirName , buildDir ) , db . findAll ( req . query ) ) ; break ; case 'getOnly' : nuxtentConfig . assetMap . set ( buildPath ( '_only' , dirName , buildDir ) , db . findOnly ( req . args , req . query ) ) ; break ; default : logger . error ( Error ( `The ${ req . method } is not supported for static builds.` ) ) ; } } ) ; } }