UNPKG

@alessiofrittoli/next-api

Version:
1 lines 2.59 kB
import {NextResponse}from'next/server';import {removeTrailingSlash}from'@alessiofrittoli/url-utils/slash';import {Exception}from'@alessiofrittoli/exception';import {generatorToReadableStream}from'@alessiofrittoli/stream-reader/utils';import {isGeneratorObject}from'@alessiofrittoli/web-utils/generators';import {ErrorCode}from'@alessiofrittoli/exception/code';var m={Exception:ErrorCode};var r=class r extends NextResponse{constructor(e={}){let{body:t,init:s,request:d,cors:n}=e;n&&r.cors(d,typeof n!="boolean"?n:void 0),super(t,r.CorsInit(s));}static json(e,t){return super.json(e,this.CorsInit(t))}static successJson(e,t){let s={message:e};return this.json(s,t)}static errorJson(e,t={}){let s=t.status||e.status||500;return t.status=s,e.status=s,this.json(e,t)}static stream(e,t){return new Response(isGeneratorObject(e)?this.generatorToStream(e):e,this.CorsInit(t))}static emptyBody(e){return this.errorJson(new Exception("Empty, invalid or locked Request Body",{code:m.Exception.EMPTY_VALUE,status:422}),e)}static cors(e,t){let s=e?.headers.get("origin")||void 0;return this.CorsOptions={...t,requestOrigin:s},this}static CorsInit(e){if(!this.CorsOptions)return e;let t=this.CorsHeaders({options:this.CorsOptions,headers:e?.headers});return this.CorsOptions=void 0,{...e,headers:t}}static CorsHeaders({options:e={},headers:t}={}){let s="*",{ALLOWED_API_ORIGINS:d}=process.env,{requestOrigin:n}=e,c=e.methods||this.CorsAllowedMethods,o=e.origin||d||s;typeof o=="string"&&o!==s&&(o=o.replace(/\s/g,"").split(",").filter(Boolean).map(removeTrailingSlash)),n&&(o.includes(removeTrailingSlash(n))||o===s)&&(o=n);let i=new Headers(t);i.set("Access-Control-Allow-Origin",o.toString()),typeof e.credentials<"u"&&i.set("Access-Control-Allow-Credentials",e.credentials.toString());let l=this.CorsAllowedHeaders.concat(e.headers||[]),u=this.CorsExposedHeaders.concat(e.exposedHeaders||[]);return l.length>0&&i.set("Access-Control-Allow-Headers",l.join(", ")),u.length>0&&i.set("Access-Control-Expose-Headers",u.join(", ")),c.length>0&&i.set("Access-Control-Allow-Methods",c.join(", ")),i}};r.CorsAllowedMethods=["GET","POST","PUT","PATCH","DELETE","OPTIONS","HEAD"],r.CorsAllowedHeaders=["Accept","Accept-Version","Authorization","Content-Length","Content-MD5","Content-Type","Date","X-Api-Key","X-Api-Version","X-CSRF-Token","X-Locale","X-Requested-With"],r.CorsExposedHeaders=["Connection","Retry-After","Keep-Alive","Date"],r.generatorToStream=generatorToReadableStream;var a=r;var j=(p,e,t=true)=>new a({body:null,init:{status:204},request:p,cors:t});export{a as NextResponse,j as corsPreflight};